xontrades1uae  SWEEP | by Bu-Rashid 
This indicator detects potential institutional exit points and reversal zones using a powerful confluence model combining:
Volume spike analysis (institutional activity)
CVD trend flips (smart money flow reversal)
Price–CVD divergence (hidden accumulation/distribution)
Liquidity sweep detection (stop-run exhaustion)
When these elements align, the indicator highlights possible Exit Flow zones, signaling where smart capital may be closing or reversing positions.
It’s optimized for XAU/USD (Gold) and NAS100 (Nasdaq) on 5-minute and 15-minute charts, with customizable strictness for traders who prefer early or confirmed signals.
Recommended use:
Apply as a confirmation layer alongside your main strategy to identify exhaustion points and institutional exits before trend reversals.
— Developed and engineered by Bu-Rashid (XonTrades1UAE)
Oscillators
Lightning Osc PreVersion2Lightning Osc PreVersion2 is a refined evolution of the earlier Lightning Osc PreVersion designed in a cleaner visual style and equipped with enhanced divergence recognition.
It continues the Lightning philosophy of precision and minimalism — built for traders who need a clear, responsive oscillator that reacts naturally to market rhythm without over-complication.
The indicator highlights the key dynamic zones at ±67.65 and ±98.7, which often mark momentum transitions, exhaustion areas, or the beginning of structural shifts.
These zones help identify when the market is entering overheated or oversold states and when it is likely to regain balance.
The divergence system tracks confirmed turning points, showing potential moments of internal reversal within the current move.
Lightning Osc PreVersion2 is crafted to read momentum clarity rather than raw noise.
It keeps the chart clean, focusing only on the essential impulses that often precede visible changes in structure.
Although it functions perfectly on its own, it works especially well when used together with Lightning Fib PreVersion — forming a powerful combination where the Fib indicator defines structure, and the Oscillator defines timing and strength.
Best Timeframes: 1m–1h
Style: non-repainting, minimal, precision momentum reading
  ,
by MahaTrend
MTF K-Means Price Regimes [matteovesperi] ⚠️ The preview uses a custom example to identify support/resistance zones. due to the fact that this identifier clusterizes, this is possible. this example was set up "in a hurry", therefore it has a possible inaccuracy. When setting up the indicator, it is extremely important to select the correct parameters and double-check them on the selected history. 
  📊 OVERVIEW 
 Purpose 
 MTF K-Means Price Regimes  is a TradingView indicator that automatically identifies and classifies the current market regime based on the K-Means machine learning algorithm. The indicator uses data from a higher timeframe (Multi-TimeFrame, MTF) to build stable classification and applies it to the working timeframe in real-time.
 Key Features 
✅  Automatic market regime detection  — the algorithm finds clusters of similar market conditions
✅  Multi-timeframe (MTF)  — clustering on higher TF, application on lower TF
✅  Adaptive  — model recalculates when a new HTF bar appears with a rolling window
✅  Non-Repainting  — classification is performed only on closed bars
✅  Visualization  — bar coloring + information panel with cluster characteristics
✅  Flexible settings  — from 2 to 10 clusters, customizable feature periods, HTF selection
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 🔬 TECHNICAL DETAILS 
 K-Means Clustering Algorithm 
 What is K-Means? 
K-Means is one of the most popular clustering algorithms (unsupervised machine learning). It divides a dataset into K groups (clusters) so that similar elements are within each cluster, and different elements are between clusters.
 Algorithm objective: 
Minimize within-cluster variance (sum of squared distances from points to their cluster center).
 How Does K-Means Work in Our Indicator? 
 Step 1: Data Collection 
The indicator accumulates history from the higher timeframe (HTF):
 
 RSI (Relative Strength Index) — overbought/oversold indicator
 ATR% (Average True Range as % of price) — volatility indicator
 ΔP% (Price Change in %) — trend strength and direction indicator
 
By default, 200 HTF bars are accumulated (clusterLookback parameter).
 Step 2: Creating Feature Vectors 
Each HTF bar is described by a three-dimensional vector:
Vector  =  
 Step 3: Normalization (Z-Score) 
All features are normalized to bring them to a common scale:
Normalized_Value = (Value - Mean) / StdDev
This is critically important, as RSI is in the range 0-100, while ATR% and ΔP% have different scales. Without normalization, one feature would dominate over others.
 Step 4: K-Means++ Centroid Initialization 
Instead of random selection of K initial centers, an improved K-Means++ method is used:
 
 First centroid is randomly selected from the data
 Each subsequent centroid is selected with probability proportional to the square of the distance to the nearest already selected centroid
 This ensures better initial centroid distribution and faster convergence
 
 Step 5: Iterative Optimization (Lloyd's Algorithm) 
Repeat until convergence (or maxIterations):
    1. Assignment step: 
       For each point find the nearest centroid and assign it to this cluster
       
    2. Update step: 
       Recalculate centroids as the average of all points in each cluster
       
    3. Convergence check:
       If centroids shifted less than 0.001 → STOP
Euclidean distance in 3D space is used:
Distance = sqrt((RSI1 - RSI2)² + (ATR1 - ATR2)² + (ΔP1 - ΔP2)²)
 Step 6: Adaptive Update 
With each new HTF bar:
 
 The oldest bar is removed from history (rolling window method)
 New bar is added to history
 K-Means algorithm is executed again on updated data
 Model remains relevant for current market conditions
 
 Real-Time Classification 
After building the model (clusters + centroids), the indicator works in classification mode:
 
 On each  closed bar  of the current timeframe, RSI, ATR%, ΔP% are calculated
 Feature vector is normalized using HTF statistics (Mean/StdDev)
 Distance to all K centroids is calculated
 Bar is assigned to the cluster with minimum distance
 Bar is colored with the corresponding cluster color
 
 Important:  Classification occurs only on a closed bar (barstate.isconfirmed), which  guarantees no repainting .
 Data Architecture 
Persistent variables (var):
├── featureVectors        - Normalized HTF feature vectors
├── centroids             - Cluster center coordinates (K * 3 values)
├── assignments           - Assignment of each HTF bar to a cluster
├── htfRsiHistory         - History of RSI values from HTF
├── htfAtrHistory         - History of ATR values from HTF
├── htfPcHistory          - History of price changes from HTF
├── htfCloseHistory       - History of close prices from HTF
├── htfRsiMean, htfRsiStd  - Statistics for RSI normalization
├── htfAtrMean, htfAtrStd  - Statistics for ATR normalization
├── htfPcMean, htfPcStd    - Statistics for Price Change normalization
├── isCalculated           - Model readiness flag
└── currentCluster         - Current active cluster
All arrays are synchronized and updated atomically when a new HTF bar appears.
 Computational Complexity 
 
 Data collection:  O(1) per bar
 K-Means (one pass): 
  - Assignment: O(N * K) where N = number of points, K = number of clusters
  - Update: O(N * K)
  - Total: O(N * K * I) where I = number of iterations (usually 5-20)
 
 Example:  With N=200 HTF bars, K=5 clusters, I=20 iterations:
200 * 5 * 20 = 20,000 operations (executes quickly)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 📖 USER GUIDE 
 Quick Start 
 1. Adding the Indicator 
TradingView → Indicators → Favorites → MTF K-Means Price Regimes
Or copy the code from mtf_kmeans_price_regimes.pine into Pine Editor.
 2. First Launch 
When adding the indicator to the chart, you'll see a table in the upper right corner:
┌─────────────────────────┐
│ Status │ Collecting HTF │
├─────────────────────────┤
│ Collected│  15 / 50     │
└─────────────────────────┘
This means the indicator is accumulating history from the higher timeframe. Wait until the counter reaches the minimum (default 50 bars for K=5).
 3. Active Operation 
After data collection is complete, the main table with cluster information will appear:
┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI  │ ATR% │ ΔP%  │ Description  │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1  │ 68.5 │ 2.15 │  1.2 │ High Vol,Bull│        │
│ 2  │ 52.3 │ 0.85 │  0.1 │ Low Vol,Flat │   ►    │
│ 3  │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│        │
└────┴──────┴──────┴──────┴──────────────┴────────┘
The arrow ► indicates the current active regime. Chart bars are colored with the corresponding cluster color.
 Customizing for Your Strategy 
 Choosing Higher Timeframe (HTF) 
 Rule:  HTF should be  at least 4 times  higher than the working timeframe.
| Working TF | Recommended HTF |
|------------|-----------------|
| 1 min      | 15 min - 1H     |
| 5 min      | 1H - 4H         |
| 15 min     | 4H - D          |
| 1H         | D - W           |
| 4H         | D - W           |
| D          | W - M           |
 HTF Selection Effect: 
 
 Lower HTF  (closer to working TF): More sensitive, frequently changing classification
 Higher HTF  (much larger than working TF): More stable, long-term regime assessment
 
 Number of Clusters (K) 
K = 2-3:  Rough division (e.g., "uptrend", "downtrend", "flat")
K = 4-5:  Optimal for most cases (DEFAULT: 5)
K = 6-8:  Detailed segmentation (requires more data)
K = 9-10: Very fine division (only for long-term analysis with large windows)
 Important constraint: 
clusterLookback ≥ numClusters * 10
I.e., for K=5 you need at least 50 HTF bars, for K=10 — at least 100 bars.
 Clustering Depth (clusterLookback) 
This is the rolling window size for building the model.
50-100 HTF bars:   Fast adaptation to market changes
200 HTF bars:      Optimal balance (DEFAULT)
500-1000 HTF bars: Long-term, stable model
 If you get an "Insufficient data" error: 
 
 Decrease clusterLookback
 Or select a lower HTF (e.g., "4H" instead of "D")
 Or decrease numClusters
 
 Color Scheme 
Default 10 colors:
 
 Red  → Often: strong bearish, high volatility
 Orange  → Transition, medium volatility
 Yellow  → Neutral, decreasing activity
 Green  → Often: strong bullish, high volatility
 Blue  → Medium bullish, medium volatility
 Purple  → Oversold, possible reversal
 Fuchsia  → Overbought, possible reversal
 Lime  → Strong upward momentum
 Aqua  → Consolidation, low volatility
 White  → Undefined regime (rare)
 
 Important:  Cluster colors are assigned randomly at each model recalculation! Don't rely on "red = bearish". Instead, look at the  description in the table  (RSI, ATR%, ΔP%).
You can customize colors in the "Colors" settings section.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 ⚙️ INDICATOR PARAMETERS 
 Main Parameters 
 Higher Timeframe (htf) 
 
 Type:  Timeframe selection
 Default:  "D" (daily)
 Description:  Timeframe on which the clustering model is built
 Recommendation:  At least 4 times larger than your working TF
 
 Clustering Depth (clusterLookback) 
 
 Type:  Integer
 Range:  50 - 2000
 Default:  200
 Description:  Number of HTF bars for building the model (rolling window size)
 Recommendation: 
  - Increase for more stable long-term model
  - Decrease for fast adaptation or if there's insufficient historical data
 
 Number of Clusters (K) (numClusters) 
 
 Type:  Integer
 Range:  2 - 10
 Default:  5
 Description:  Number of market regimes the algorithm will identify
 Recommendation: 
  - K=3-4 for simple strategies (trending/ranging)
  - K=5-6 for universal strategies
  - K=7-10 only when clusterLookback ≥ 100*K
 
 Max K-Means Iterations (maxIterations) 
 
 Type:  Integer
 Range:  5 - 50
 Default:  20
 Description:  Maximum number of algorithm iterations
 Recommendation: 
  - 10-20 is sufficient for most cases
  - Increase to 30-50 if using K > 7
 
 Feature Parameters 
 RSI Period (rsiLength) 
 
 Type:  Integer
 Default:  14
 Description:  Period for RSI calculation (overbought/oversold feature)
 Recommendation: 
  - 14 — standard
  - 7-10 — more sensitive
  - 20-25 — more smoothed
 
 ATR Period (atrLength) 
 
 Type:  Integer
 Default:  14
 Description:  Period for ATR calculation (volatility feature)
 Recommendation:  Usually kept equal to rsiLength
 
 Price Change Period (pcLength) 
 
 Type:  Integer
 Default:  5
 Description:  Period for percentage price change calculation (trend feature)
 Recommendation: 
  - 3-5 — short-term trend
  - 10-20 — medium-term trend
 
 Visualization 
 Show Info Panel (showDashboard) 
 
 Type:  Checkbox
 Default:  true
 Description:  Enables/disables the information table on the chart
 
 Cluster Color 1-10 
 
 Type:  Color selection
 Description:  Customize colors for visual cluster distinction
 Recommendation:  Use contrasting colors for better readability
 
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 📊 INTERPRETING RESULTS 
 Reading the Information Table 
┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI  │ ATR% │ ΔP%  │ Description  │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1  │ 68.5 │ 2.15 │  1.2 │ High Vol,Bull│        │
│ 2  │ 52.3 │ 0.85 │  0.1 │ Low Vol,Flat │   ►    │
│ 3  │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│        │
│ 4  │ 45.0 │ 1.20 │ -0.3 │ Low Vol,Bear │        │
│ 5  │ 72.1 │ 3.05 │  2.8 │ High Vol,Bull│        │
└────┴──────┴──────┴──────┴──────────────┴────────┘
 "ID" Column 
Cluster number (1-K). Order doesn't matter.
 "RSI" Column 
Average RSI value in the cluster (0-100):
 
 < 30:  Oversold zone
 30-45:  Bearish sentiment
 45-55:  Neutral zone
 55-70:  Bullish sentiment
 > 70:  Overbought zone
 
 "ATR%" Column 
Average volatility in the cluster (as % of price):
 
 < 1%:  Low volatility (consolidation, narrow range)
 1-2%:  Normal volatility
 2-3%:  Elevated volatility
 > 3%:  High volatility (strong movements, impulses)
 
Compared to the average volatility across all clusters to determine "High Vol" or "Low Vol".
 "ΔP%" Column 
Average price change in the cluster (in % over pcLength period):
 
 > +0.05%:  Bullish regime
 -0.05% ... +0.05%:  Flat (sideways movement)
 < -0.05%:  Bearish regime
 
 "Description" Column 
Automatic interpretation:
 
 "High Vol, Bull"  → Strong upward momentum, high activity
 "Low Vol, Flat"  → Consolidation, narrow range, uncertainty
 "High Vol, Bear"  → Strong decline, panic, high activity
 "Low Vol, Bull"  → Slow growth, low activity
 "Low Vol, Bear"  → Slow decline, low activity
 
 "Current" Column 
Arrow  ►  shows which cluster the  last closed bar  of your working timeframe is in.
 Typical Cluster Patterns 
 Example 1: Trend/Flat Division (K=3) 
Cluster 1: RSI=65, ATR%=2.5, ΔP%=+1.5  → Bullish trend
Cluster 2: RSI=50, ATR%=0.8, ΔP%=0.0   → Flat/Consolidation
Cluster 3: RSI=35, ATR%=2.3, ΔP%=-1.4  → Bearish trend
 Strategy:  Open positions when regime changes Flat → Trend, avoid flat.
 Example 2: Volatility Breakdown (K=5) 
Cluster 1: RSI=72, ATR%=3.5, ΔP%=+2.5  → Strong bullish impulse (high risk)
Cluster 2: RSI=60, ATR%=1.5, ΔP%=+0.8  → Moderate bullish (optimal entry point)
Cluster 3: RSI=50, ATR%=0.7, ΔP%=0.0   → Flat
Cluster 4: RSI=40, ATR%=1.4, ΔP%=-0.7  → Moderate bearish
Cluster 5: RSI=28, ATR%=3.2, ΔP%=-2.3  → Strong bearish impulse (panic)
 Strategy:  Enter in Cluster 2 or 4, avoid extremes (1, 5).
 Example 3: Mixed Regimes (K=7+) 
With large K, clusters can represent condition combinations:
 
 High RSI + Low volatility → "Quiet overbought"
 Neutral RSI + High volatility → "Uncertainty with high activity"
 Etc.
 
Requires individual analysis of each cluster.
 Regime Changes 
 Important signal:  Transition from one cluster to another!
Trading situation examples:
 
 Flat → Bullish trend  → Buy signal
 Bullish trend → Flat  → Take profit, close longs
 Flat → Bearish trend  → Sell signal
 Bearish trend → Flat  → Close shorts, wait
 
You can build a trading system based on the current active cluster and transitions between them.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 💡 USAGE EXAMPLES 
 Example 1: Scalping with HTF Filter 
 Task:  Scalping on 5-minute charts, but only enter in the direction of the daily regime.
 Settings: 
 
 Working TF: 5 min
 HTF: D (daily)
 K: 3 (simple division)
 clusterLookback: 100
 
 Logic: 
IF current cluster = "Bullish" (ΔP% > 0.5)
   → Look for long entry points on 5M
   
IF current cluster = "Bearish" (ΔP% < -0.5)
   → Look for short entry points on 5M
   
IF current cluster = "Flat"
   → Don't trade / reduce risk
 Example 2: Swing Trading with Volatility Filtering 
 Task:  Swing trading on 4H, enter only in regimes with medium volatility.
 Settings: 
 
 Working TF: 4H
 HTF: D (daily)
 K: 5
 clusterLookback: 200
 
 Logic: 
Allowed clusters for entry:
- ATR% from 1.5% to 2.5% (not too quiet, not too chaotic)
- ΔP% with clear direction (|ΔP%| > 0.5)
Prohibited clusters:
- ATR% > 3% → Too risky (possible gaps, sharp reversals)
- ATR% < 1% → Too quiet (small movements, commissions eat profit)
 Example 3: Portfolio Rotation 
 Task:  Managing a portfolio of multiple assets, allocate capital depending on regimes.
 Settings: 
 
 Working TF: D (daily)
 HTF: W (weekly)
 K: 4
 clusterLookback: 100
 
 Logic: 
For each asset in portfolio:
IF regime = "Strong trend + Low volatility"
   → Increase asset weight in portfolio (40-50%)
   
IF regime = "Medium trend + Medium volatility"
   → Standard weight (20-30%)
   
IF regime = "Flat" or "High volatility without trend"
   → Minimum weight or exclude (0-10%)
 Example 4: Combining with Other Indicators 
 MTF K-Means as a filter: 
Main strategy: MA Crossover
Filter: MTF K-Means on higher TF
Rule:
  IF MA_fast > MA_slow  AND  Cluster = "Bullish regime"
     → LONG
     
  IF MA_fast < MA_slow  AND  Cluster = "Bearish regime"
     → SHORT
     
  ELSE
     → Don't trade (regime doesn't confirm signal)
This dramatically reduces false signals in unsuitable market conditions.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 📈 OPTIMIZATION RECOMMENDATIONS 
 Optimal Settings for Different Styles 
 Day Trading 
Working TF: 5M - 15M
HTF: 1H - 4H
numClusters: 4-5
clusterLookback: 100-150
 Swing Trading 
Working TF: 1H - 4H
HTF: D
numClusters: 5-6
clusterLookback: 150-250
 Position Trading 
Working TF: D
HTF: W - M
numClusters: 4-5
clusterLookback: 100-200
 Scalping 
Working TF: 1M - 5M
HTF: 15M - 1H
numClusters: 3-4
clusterLookback: 50-100
 Backtesting 
To evaluate effectiveness:
 
 Load historical data  (minimum 2x clusterLookback HTF bars)
 Apply the indicator  with your settings
 Study cluster change history: 
   - Do changes coincide with actual trend transitions?
   - How often do false signals occur?
 Optimize parameters: 
   - If too much noise → increase HTF or clusterLookback
   - If reaction too slow → decrease HTF or increase numClusters
 
 Combining with Other Techniques 
 Regime-Based Approach: 
MTF K-Means (regime identification)
    ↓
+---+---+---+
|   |   |   |
v   v   v   v
Trend  Flat  High_Vol  Low_Vol
  ↓     ↓       ↓         ↓
Strategy_A  Strategy_B  Don't_trade
Examples:
 
 Trend:  Use trend-following strategies (MA crossover, Breakout)
 Flat:  Use mean-reversion strategies (RSI, Bollinger Bands)
 High volatility:  Reduce position sizes, widen stops
 Low volatility:  Expect breakout, don't open positions inside range
 
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 📞 SUPPORT 
 Report an Issue 
If you found a bug or have a suggestion for improvement:
 
 Describe the problem in as much detail as possible
 Specify your indicator settings
 Attach a screenshot (if possible)
 Specify the asset and timeframe where the problem is observed
Fakeout Kavach by Pooja v10📘 Description – Fakeout Kavach by Pooja
Fakeout Kavach by Pooja is a precision-built technical analysis tool designed for structured momentum and divergence evaluation within the RSI pane.
It helps visualize potential exhaustion zones using RSI divergence, ADX trend confirmation, and an integrated VAD (Volume + ATR + Delta) module — ensuring clarity and confirmation-based plotting.
⚙️ Core Functional Modules
1️⃣ RSI & Moving Average Module
Adaptive RSI with real-time color gradients
Optional RSI moving average (yellow) for momentum tracking
Dynamic fill zones showing overbought / oversold areas
Background fill for quick zone visualization
2️⃣ RSI Divergence Detection (Bull / Bear)
Auto-detects pivot-based bullish and bearish divergences
Non-repainting logic confirmed post-pivot formation
Smart line management with automatic cleanup
Visual divergence lines and clear on-chart markers
3️⃣ ADX Trend Confirmation
Adjustable comparison: “Higher than N bars ago” or “Higher than highest of last N”
Confirms directional strength before SB / SS signals are displayed
4️⃣ SB / SS Signal Module
“Signal Bull / Signal Sell” markers confirmed post candle closure
Integrated session-block feature to exclude specific intraday periods
Non-repainting, bar-confirmed signal plotting
5️⃣ VAD (Volume + ATR + Delta) Divergence Engine
Highlights hidden momentum shifts via volatility + volume flow logic
Bullish (B-DV) / Bearish (S-DV) divergence markers plotted at pivot bars
Customizable label or symbol-style visualization
🧩 Built-in Features
Non-repainting structure using barstate confirmation
Optimized for all timeframes and chart types
Lightweight execution with flexible styling options
Modular input control for easy customization
⚠️ Disclaimer
This indicator is for technical analysis and educational purposes only.
It does not provide financial advice, does not predict price direction, and does not guarantee profits or performance.
All trading decisions are the sole responsibility of the user. Always test thoroughly before applying to live markets.
Lightning Osc • PreVersion 
The Lightning Osc • PreVersion is where the MahaTrend vision began —
the first oscillator designed to visualize the pulse of the market itself.
It reveals how momentum expands, cools down, and reverses through natural rhythm,
allowing you to see balance and exhaustion with clarity and precision.
This is the original core from which every Lightning indicator later evolved —
simple, focused, and deeply intuitive.
🧭 Purpose
The indicator highlights overbought and oversold rhythm zones,
helping traders recognize when the market may have reached its energetic limits.
Rather than generating signals, it visualizes the transitions of energy
— the quiet shift that often happens before price movement changes direction.
💡 Core Logic
When the curve moves above +67.65, the market enters an overbought zone.
The most informative moment is the break below and retest of that boundary —
it often reflects fading upward strength and possible correction.
When the curve dips below −67.65, the market enters an oversold zone.
A break above and retest of this area may show that selling pressure is exhausted
and the market is ready for relief or reversal.
These levels do not dictate trades — they show rhythm
so you can understand when momentum begins to breathe again.
⏱ Recommended Timeframes
Optimized for 1-minute to 1-hour charts,
the Lightning Osc • PreVersion is most expressive on lower timeframes
where short-term volatility and energy flow are clearly visible.
🧩 How to Use
Add the indicator to a separate pane below your chart.
Choose the calculation timeframe (default: current chart TF).
Observe the curve:
Above +67.65 → Overbought zone
Below −67.65 → Oversold zone
±4.6 → Micro-pulse equilibrium
Focus on break & retest behavior near key zones —
these moments often reveal changing market rhythm.
Always confirm with your broader context and personal strategy.
🌩 Philosophy
This PreVersion marks the beginning of the Lightning language —
a balance between structure and flow,
between overextension and calm restoration.
It embodies the MahaTrend idea that the market is not chaos,
but an energy field breathing in and out through rhythm.
Disclaimer:
For educational and analytical use only.
This indicator does not provide financial advice or guaranteed results.
Always combine it with your own analysis and risk management.
— by MahaTrend
SigmaKernel - AdaptiveSigmaKernel - Adaptive  Self-Optimizing Multi-Factor Trading System
SigmaKernel - Adaptive is a self-learning algorithmic trading strategy that combines four distinct analytical dimensions—momentum, market structure, volume flow, and reversal patterns—within a machine-learning-inspired framework that continuously adjusts its own parameters based on realized trading performance. Unlike traditional fixed-parameter strategies that maintain static weightings regardless of market conditions or results, this system implements a feedback loop that tracks which signal types, directional biases, and market conditions produce profitable outcomes, then mathematically adjusts component weightings, minimum score thresholds, position sizing multipliers, and trade spacing requirements to optimize future performance.
The strategy is designed for futures traders operating on prop firm accounts or live capital, incorporating realistic execution mechanics including configurable entry modes (stop breakout orders, limit pullback entries, or market-on-open), commission structures calibrated to retail futures contracts ($0.62 per contract default), one-tick slippage modeling, and professional risk controls including trailing drawdown guards, daily loss limits, and weekly profit targets. The system features universal futures compatibility—it automatically detects and adapts to any futures contract by reading the instrument's tick size and point value directly from the chart, eliminating the need for manual configuration across different markets.
 What Makes This Approach Different 
 Adaptive Weight Optimization System 
The core differentiation is the adaptive learning architecture. The strategy maintains four independent scoring components: momentum analysis (using RSI multi-timeframe, MACD histogram, and DMI/ADX), market structure detection (breakout identification via pivot-based support/resistance and moving average positioning), volume flow analysis (Volume Price Trend indicator with standard deviation confirmation), and reversal pattern recognition (oversold/overbought conditions combined with structural levels).
Each component generates a directional score that is multiplied by its current weight. After every closed trade, the system performs a retrospective analysis on the last N trades (configurable Learning Period, default 15 trades) to calculate win rates for each signal type independently. For example, if momentum-driven trades won 65% of the time while reversal trades won only 35%, the adaptive algorithm increases the momentum weight and decreases the reversal weight proportionally. The adjustment formula is:
New_Weight = Current_Weight + (Component_Win_Rate - Average_Win_Rate) × Adaptation_Speed
This creates a self-correcting mechanism where successful signal generators receive more influence in future composite scores, while underperforming components are de-emphasized. The system separately tracks long versus short win rates and applies directional bias corrections—if shorts consistently outperform longs, the strategy applies a 10% reduction to bullish signals to prevent fighting the prevailing market character.
 Dynamic Parameter Adjustment 
Beyond component weightings, three critical strategy parameters self-adjust based on performance:
 Minimum Signal Score:  The threshold required to trigger a trade. If overall win rate falls below 45%, the system increments this threshold by 0.10 per adjustment cycle, making the strategy more selective. If win rate exceeds 60%, the threshold decreases to allow more opportunities. This prevents the strategy from overtrading during unfavorable conditions and capitalizes on high-probability environments.
 Risk Multiplier:  Controls position sizing aggression. When drawdown exceeds 5%, risk per trade reduces by 10% per cycle. When drawdown falls below 2%, risk increases by 5% per cycle. This implements the professional risk management principle of "bet small when losing, bet bigger when winning" algorithmically.
 Bars Between Trades:  Spacing filter to prevent overtrading. Base value (default 9 bars) multiplies by drawdown factor and losing streak factor. During drawdown or consecutive losses, spacing expands up to 2x to allow market conditions to change before re-entering.
All adaptation operates during live forward-testing or real trading—there is no in-sample optimization applied to historical data. The system learns solely from its own realized trades.
 Universal Futures Compatibility 
The strategy implements universal futures instrument detection that automatically adapts to any futures contract without requiring manual configuration. Instead of hardcoding specific contract specifications, the system reads three critical values directly from TradingView's symbol information:
 Tick Size Detection:  Uses `syminfo.mintick` to obtain the minimum price increment for the current instrument. This value varies widely across markets—ES trades in 0.25 ticks, crude oil (CL) in 0.01 ticks, gold (GC) in 0.10 ticks, and treasury futures (ZB) in increments of 1/32nds. The strategy adapts all entry buffer calculations and stop placement logic to the detected tick size.
 Point Value Detection:  Uses `syminfo.pointvalue` to determine the dollar value per full point of price movement. For ES, one point equals $50; for crude oil, one point equals $1,000; for gold, one point equals $100. This automatic detection ensures accurate P&L calculations and risk-per-contract measurements across all instruments.
 Tick Value Calculation:  Combines tick size and point value to compute dollar value per tick: Tick_Value = Tick_Size × Point_Value. This derived value drives all position sizing calculations, ensuring the risk management system correctly accounts for each instrument's economic characteristics.
This universal approach means the strategy functions identically on emini indices (ES, MES, NQ, MNQ), micro indices, energy contracts (CL, NG, RB), metals (GC, SI, HG), agricultural futures (ZC, ZS, ZW), treasury futures (ZB, ZN, ZF), currency futures (6E, 6J, 6B), and any other futures contract available on TradingView. No parameter adjustments or instrument-specific branches exist in the code—the adaptation happens automatically through symbol information queries.
 Stop-Out Rate Monitoring System 
The strategy includes an intelligent stop-out rate tracking system that monitors the percentage of your last 20 trades (or available trades if fewer than 20) that were stopped out. This metric appears in the dashboard's Performance section with color-coded guidance:
 Green (<30% stop-out rate):  Very few trades are being stopped out. This suggests either your stops are too loose (giving back profits on reversals) or you're in an exceptional trending market. Consider tightening your Stop Loss ATR multiplier to lock in profits more efficiently.
 Orange (30-65% stop-out rate):  Healthy range. Your stop placement is appropriately sized for current market conditions and the strategy's risk-reward profile. No adjustment needed.
 Red (>65% stop-out rate):  Too many trades are being stopped out prematurely. Your stops are likely too tight for the current volatility regime. Consider widening your Stop Loss ATR multiplier to give trades more room to develop.
 Critical Design Philosophy:  Unlike some systems that automatically adjust stops based on performance statistics, this strategy intentionally keeps stop-loss control in the user's hands. Automatic stop adjustment creates dangerous feedback loops—widening stops increases risk per contract, which forces position size reduction, which distorts performance metrics, leading to incorrect adaptations. Instead, the dashboard provides visibility into stop performance, empowering you to make informed manual adjustments when warranted. This preserves the integrity of the adaptive system while giving you the critical data needed for stop optimization.
 Execution Kernel Architecture 
The entry system offers three distinct execution modes to match trader preference and market character:
 StopBreakout Mode:  Places buy-stop orders above the prior bar's high (for longs) or sell-stop orders below the prior bar's low (for shorts), plus a 2-tick buffer. This ensures entries only occur when price confirms directional momentum by breaking recent structure. Ideal for trending and momentum-driven markets.
 LimitPullback Mode:  Places limit orders at a pullback price calculated as: Entry_Price = Close - (ATR × Pullback_Multiplier) for longs, or Close + (ATR × Pullback_Multiplier) for shorts. Default multiplier is 0.5 ATR. This waits for mean-reversion before entering in the signal direction, capturing better prices in volatile or oscillating markets.
 MarketNextOpen Mode:  Executes at market on the bar immediately following signal generation. This provides fastest execution but sacrifices the filtering effect of requiring price confirmation.
All pending entry orders include a configurable Time-To-Live (TTL, default 6 bars). If an order is not filled within the TTL period, it cancels automatically to prevent stale signals from executing in changed market conditions.
 Professional Exit Management 
The exit system implements a three-stage progression: initial stop loss, breakeven adjustment, and dynamic trailing stop.
 Initial Stop Loss:  Calculated as entry price ± (ATR × User_Stop_Multiplier × Volatility_Adjustment). Users have direct control via the Stop Loss ATR multiplier (default 1.25). The system then applies volatility regime adjustments: ×1.2 in high-volatility environments (stops automatically widen), ×0.8 in low volatility (stops tighten), ×1.0 in normal conditions. This ensures stops adapt to market character while maintaining user control over baseline risk tolerance.
 Breakeven Trigger:  When profit reaches a configurable multiple of initial risk (default 1.0R), the stop loss automatically moves to breakeven (entry price). This locks in zero-loss status once the trade demonstrates favorable movement.
 Trailing Stop Activation:  When profit reaches the Trail_Trigger_R multiple (default 1.2R), the system cancels the fixed stop and activates a dynamic trailing stop. The trail uses Step and Offset parameters defined in R-multiples. For example, with Trail_Offset_R = 1.0 and Trail_Step_R = 1.5, the stop trails 1.0R behind price and moves in 1.5R increments. This captures extended moves while protecting accumulated profit.
Additional failsafes include maximum time-in-trade (exits after N bars if specified) and end-of-session flatten (automatically closes all positions X minutes before session end to avoid overnight exposure).
 Core Calculation Methodology 
 Signal Component Scoring 
 Momentum Component: 
- Calculates 14-period DMI (Directional Movement Index) with ADX strength filter (trending when ADX > 25)
- Computes three RSI timeframes: fast (7-period), medium (14-period), slow (21-period)
- Analyzes MACD (12/26/9) histogram for directional acceleration
- Bullish momentum: uptrend (DI+ > DI- with ADX > 25) + MACD histogram rising above zero + RSI fast between 50-80 = +1.6 score
- Bearish momentum: downtrend (DI- > DI+ with ADX > 25) + MACD histogram falling below zero + RSI fast between 20-50 = -1.6 score
- Score multiplies by volatility adjustment factor: ×0.8 in high volatility (momentum less reliable), ×1.2 in low volatility (momentum more persistent)
 Structure Component: 
- Identifies swing highs and lows using 10-bar pivot lookback on both sides
- Maintains most recent swing high as dynamic resistance, most recent swing low as dynamic support
- Detects breakouts: bullish when close crosses above resistance with prior bar below; bearish when close crosses below support with prior bar above
- Breakout score: ±1.0 for confirmed break
- Moving average alignment: +0.5 when price > SMA20 > SMA50 (bullish structure); -0.5 when price < SMA20 < SMA50 (bearish structure)
- Total structure range: -1.5 to +1.5
 Volume Component: 
- Calculates Volume Price Trend: VPT = Σ [(Close - Close ) / Close  × Volume]
- Compares VPT to its 10-period EMA as signal line (similar to MACD logic)
- Computes 20-period volume moving average and standard deviation
- High volume event: current volume > (volume_average + 1× std_dev)
- Bullish volume: VPT > VPT_signal AND high_volume = +1.0
- Bearish volume: VPT < VPT_signal AND high_volume = -1.0
- No score if volume is not elevated (filters out low-conviction moves)
 Reversal Component: 
- Identifies extreme RSI conditions: RSI slow < 30 (oversold) or > 70 (overbought)
- Requires structural confluence: price at or below support level for bullish reversal; at or above resistance for bearish reversal
- Requires momentum shift: RSI fast must be rising (for bull) or falling (for bear) to confirm reversal in progress
- Bullish reversal: RSI < 30 AND price ≤ support AND RSI rising = +1.0
- Bearish reversal: RSI > 70 AND price ≥ resistance AND RSI falling = -1.0
 Composite Score Calculation 
Final_Score = (Momentum × Weight_M) + (Structure × Weight_S) + (Volume × Weight_V) + (Reversal × Weight_R)
Initial weights: Momentum = 1.0, Structure = 1.2, Volume = 0.8, Reversal = 0.6
These weights adapt after each trade based on component-specific performance as described above.
The system also applies directional bias adjustment: if recent long trades have significantly lower win rate than shorts, bullish scores multiply by 0.9 to reduce aggressive long entries. Vice versa for underperforming shorts.
 Position Sizing Algorithm 
The position sizing calculation incorporates multiple confidence factors and automatically scales to any futures contract:
1. Base risk amount = Account_Size × Base_Risk_Percent × Adaptive_Risk_Multiplier
2. Stop distance in price units = ATR × User_Stop_Multiplier × Volatility_Regime_Multiplier × Entry_Buffer
3. Risk per contract = Stop_Distance × Dollar_Per_Point (automatically detected from instrument)
4. Raw position size = Risk_Amount / Risk_Per_Contract
Then applies confidence scaling:
- Signal confidence = min(|Weighted_Score| / Min_Score_Threshold, 2.0) — higher scores receive larger size, capped at 2×
- Direction confidence = Long_Win_Rate (for bulls) or Short_Win_Rate (for bears)
- Type confidence = Win_Rate of dominant signal type (momentum/structure/volume/reversal)
- Total confidence = (Signal_Confidence + Direction_Confidence + Type_Confidence) / 3
Adjusted size = Raw_Size × Total_Confidence × Losing_Streak_Reduction
Losing streak reduction = 0.5 if losing_streak ≥ 5, otherwise 1.0
 Universal Maximum Position Calculation:  Instead of hardcoded limits per instrument, the system calculates maximum position size as: Max_Contracts = Account_Size / 25000, clamped between 1 and 10 contracts. This means a $50,000 account allows up to 2 contracts, a $100,000 account allows up to 4 contracts, regardless of which futures contract is being traded. This universal approach maintains consistent risk exposure across different instruments while preventing overleveraging.
Final size is rounded to integer and bounded by the calculated maximum.
 Session and Risk Management System 
 Timezone-Aware Session Control 
The strategy implements timezone-correct session filtering. Users specify session start hour, end hour, and timezone from 12 supported zones (New York, Chicago, Los Angeles, London, Frankfurt, Moscow, Tokyo, Hong Kong, Shanghai, Singapore, Sydney, UTC). The system converts bar timestamps to the selected timezone before applying session logic.
For split sessions (e.g., Asian session 18:00-02:00), the logic correctly handles time wraparound. Weekend trading can be optionally disabled (default: disabled) to avoid low-liquidity weekend price action.
 Multi-Layer Risk Controls 
 Daily Loss Limit:  Strategy ceases all new entries when daily P&L reaches negative threshold (default $2,000). This prevents catastrophic drawdown days. Resets at timezone-corrected day boundary.
 Weekly Profit Target:  Strategy ceases trading when weekly profit reaches target (default $10,000). This implements the professional principle of "take the win and stop pushing luck." Resets on timezone-corrected Monday.
 Maximum Daily Trades:  Hard cap on entries per day (default 20) to prevent overtrading during volatile conditions when many signals may generate.
 Trailing Drawdown Guard:  Optional prop-firm-style trailing stop on account equity. When enabled, if equity drops below (Peak_Equity - Trailing_DD_Amount), all trading halts. This simulates the common prop firm rule where exceeding trailing drawdown results in account termination.
All limits display status in the real-time dashboard, showing "MAX LOSS HIT", "WEEKLY TARGET MET", or "ACTIVE" depending on current state.
 How To Use This Strategy 
 Initial Setup 
1. Apply the strategy to your desired futures chart (tested on 5-minute through daily timeframes)
2. The strategy will automatically detect your instrument's specifications—no manual configuration needed for different contracts
3. Configure your account size and risk parameters in the Core Settings section
4. Set your trading session hours and timezone to match your availability
5. Adjust the Stop Loss ATR multiplier based on your risk tolerance (0.8-1.2 for tighter stops, 1.5-2.5 for wider stops)
6. Select your preferred entry execution mode (recommend StopBreakout for beginners)
7. Enable adaptation (recommended) or disable for fixed-parameter operation
8. Review the strategy's Properties in the Strategy Tester settings and verify commission/slippage match your broker's actual costs
The universal futures detection means you can switch between ES, NQ, CL, GC, ZB, or any other futures contract without changing any strategy parameters—the system will automatically adapt its calculations to each instrument's unique specifications.
 Dashboard Interpretation 
The strategy displays a comprehensive real-time dashboard in the top-right corner showing:
 Market State Section: 
- Trend: Shows UPTREND/DOWNTREND/CONSOLIDATING/NEUTRAL based on ADX and DMI analysis
- ADX Value: Current trend strength (>25 = strong trend, <20 = consolidating)
- Momentum: BULL/BEAR/NEUTRAL classification with current momentum score
- Volatility: HIGH/LOW/NORMAL regime with ATR percentage of price
 Volume Profile Section (Large dashboard only): 
- VPT Flow: Directional bias from volume analysis
- Volume Status: HIGH/LOW/NORMAL with relative volume multiplier
 Performance Section: 
- Daily P&L: Current day's profit/loss with color coding
- Daily Trades: Number of completed trades today
- Weekly P&L: Current week's profit/loss
- Target %: Progress toward weekly profit target
- Stop-Out Rate: Percentage of last 20 trades (or available trades if <20) that were stopped out. Includes all stop types: initial stops, breakeven stops, trailing stops, timeout exits, and EOD flattens. Color coded with actionable guidance:
  - Green (<30%): Shows "TIGHTEN" guidance. Very few stop-outs suggests stops may be too loose or exceptional market conditions. Consider reducing Stop Loss ATR multiplier.
  - Orange (30-65%): Shows "OK" guidance. Healthy stop-out rate indicating appropriate stop placement for current conditions.
  - Red (>65%): Shows "WIDEN" guidance. Too many premature stop-outs. Consider increasing Stop Loss ATR multiplier to give trades more room.
- Status: Overall trading status (ACTIVE/MAX LOSS HIT/WEEKLY TARGET MET/FILTERS ACTIVE)
 Adaptive Engine Section: 
- Min Score: Current minimum threshold for trade entry (higher = more selective)
- Risk Mult: Current position sizing multiplier (adjusts with performance)
- Bars BTW: Current minimum bars required between trades
- Drawdown: Current drawdown percentage from equity peak
- Weights: M/S/V/R showing current component weightings
 Win Rates Section: 
- Type: Win rates for Momentum, Structure, Volume, Reversal signal types
- Direction: Win rates for Long vs Short trades
Color coding shows green for >50% win rate, red for <50%
 Session Info Section: 
- Session Hours: Active trading window with timezone
- Weekend Trading: ENABLED/DISABLED status
- Session Status: ACTIVE/INACTIVE based on current time
 Signal Generation and Entry 
The strategy generates entries when the weighted composite score exceeds the adaptive minimum threshold (initial value configurable, typically 1.5 to 2.5). Entries display as layered triangle markers on the chart:
- Long Signal: Three green upward triangles below the entry bar
- Short Signal: Three red downward triangles above the entry bar
Triangle tooltip shows the signal score and dominant signal type (MOMENTUM/STRUCTURE/VOLUME/REVERSAL).
 Position Management and Stop Optimization 
Once entered, the strategy automatically manages the position through its three-stage exit system. Monitor the Stop-Out Rate metric in the dashboard to optimize your stop placement:
 If Stop-Out Rate is Green (<30%):  You're rarely being stopped out. This could mean:
- Your stops are too loose, allowing trades to give back too much profit on reversals
- You're in an exceptional trending market where tight stops would work better
- Action: Consider reducing your Stop Loss ATR multiplier by 0.1-0.2 to tighten stops and lock in profits more efficiently
 If Stop-Out Rate is Orange (30-65%):  Optimal range. Your stops are appropriately sized for the strategy's risk-reward profile and current market volatility. No adjustment needed.
 If Stop-Out Rate is Red (>65%):  You're being stopped out too frequently. This means:
- Your stops are too tight for current market volatility
- Trades need more room to develop before reaching profit targets
- Action: Increase your Stop Loss ATR multiplier by 0.1-0.3 to give trades more breathing room
Remember: The stop-out rate calculation includes all exit types (initial stops, breakeven stops, trailing stops, timeouts, EOD flattens). A trade that reaches breakeven and gets stopped out at entry price counts as a stop-out, even though it didn't lose money. This is intentional—it indicates the stop placement didn't allow the trade to develop into profit.
 Optimization Workflow 
For traders wanting to customize the strategy for their specific instrument and timeframe:
 Week 1-2: Run with defaults, adaptation enabled 
Allow the system to execute at least 30-50 trades (the Learning Period plus additional buffer). Monitor which session periods, signal types, and market conditions produce the best results. Observe your stop-out rate—if it's consistently red or green, plan to adjust Stop Loss ATR multiplier after the learning period. Do not adjust parameters yet—let the adaptive system establish baseline performance data.
 Week 3-4: Analyze adaptation behavior and optimize stops 
Review the dashboard's adaptive weights and win rates. If certain signal types consistently show <40% win rate, consider slightly reducing their base weight. If a particular entry mode produces better fill quality and win rate, switch to that mode. If you notice the minimum score threshold has climbed very high (>3.0), market conditions may not suit the strategy's logic—consider switching instruments or timeframes.
Based on your Stop-Out Rate observations:
- Consistently <30%: Reduce Stop Loss ATR multiplier by 0.2-0.3
- Consistently >65%: Increase Stop Loss ATR multiplier by 0.2-0.4
- Oscillating between zones: Leave stops at default and let volatility regime adjustments handle it
 Ongoing: Fine-tune risk and execution 
Adjust the following based on your risk tolerance and account type:
- Base Risk Per Trade: 0.5% for conservative, 0.75% for moderate, 1.0% for aggressive
- Stop Loss ATR Multiplier: 0.8-1.2 for tight stops (scalping), 1.5-2.5 for wide stops (swing trading)
- Bars Between Trades: Lower (5-7) for more opportunities, higher (12-20) for more selective
- Entry Mode: Experiment between modes to find best fit for current market character
- Session Hours: Narrow to specific high-performance session windows if certain hours consistently underperform
 Never adjust:  Do not manually modify the adaptive weights, minimum score, or risk multiplier after the system has begun learning. These parameters are self-optimizing and manual interference defeats the adaptive mechanism.
 Parameter Descriptions and Optimization Guidelines 
 Adaptive Intelligence Group 
 Enable Self-Optimization (default: true):  Master switch for the adaptive learning system. When enabled, component weights, minimum score, risk multiplier, and trade spacing adjust based on realized performance. Disable to run the strategy with fixed parameters (useful for comparing adaptive vs non-adaptive performance).
 Learning Period (default: 15 trades):  Number of most recent trades to analyze for performance calculations. Shorter values (10-12) adapt more quickly to recent conditions but may overreact to variance. Longer values (20-30) produce more stable adaptations but respond slower to regime changes. For volatile markets, use shorter periods. For stable trends, use longer periods.
 Adaptation Speed (default: 0.25):  Controls the magnitude of parameter adjustments per learning cycle. Lower values (0.05-0.15) make gradual, conservative changes. Higher values (0.35-0.50) make aggressive adjustments. Faster adaptation helps in rapidly changing markets but increases parameter instability. Start with default and increase only if you observe the system failing to adapt quickly enough to obvious performance patterns.
 Performance Memory (default: 100 trades):  Maximum number of historical trades stored for analysis. This array size does not affect learning (which uses only Learning Period trades) but provides data for future analytics features including stop-out rate tracking. Higher values consume more memory but provide richer historical dataset. Typical users should not need to modify this.
 Core Settings Group 
 Account Size (default: $50,000):  Starting capital for position sizing calculations. This should match your actual account size for accurate risk per trade. The strategy uses this value to calculate dollar risk amounts and determine maximum position size (1 contract per $25,000).
 Weekly Profit Target (default: $10,000):  When weekly P&L reaches this value, the strategy stops taking new trades for the remainder of the week. This implements a "quit while ahead" rule common in professional trading. Set to a realistic weekly goal—20% of account size per week ($10K on $50K) is very aggressive; 5-10% is more sustainable.
 Max Daily Loss (default: $2,000):  When daily P&L reaches this negative threshold, strategy stops all new entries for the day. This is your maximum acceptable daily loss. Professional traders typically set this at 2-4% of account size. A $2,000 loss on a $50,000 account = 4%.
 Base Risk Per Trade % (default: 0.5%):  Initial percentage of account to risk on each trade before adaptive multiplier and confidence scaling. 0.5% is conservative, 0.75% is moderate, 1.0-1.5% is aggressive. Remember that actual risk per trade = Base Risk × Adaptive Risk Multiplier × Confidence Factors, so the realized risk will vary.
 Trade Filters Group 
 Base Minimum Signal Score (default: 1.5):  Initial threshold that composite weighted score must exceed to generate a signal. Lower values (1.0-1.5) produce more trades with lower average quality. Higher values (2.0-3.0) produce fewer, higher-quality setups. This value adapts automatically when adaptive mode is enabled, but the base sets the starting point. For trending markets, lower values work well. For choppy markets, use higher values.
 Base Bars Between Trades (default: 9):  Minimum bars that must elapse after an entry before another signal can trigger. This prevents overtrading and allows previous trades time to develop. Lower values (3-6) suit scalping on lower timeframes. Higher values (15-30) suit swing trading on higher timeframes. This value also adapts based on drawdown and losing streaks.
 Max Daily Trades (default: 20):  Hard limit on total trades per day regardless of signal quality. This prevents runaway trading during extremely volatile days when many signals may generate. For 5-minute charts, 20 trades/day is reasonable. For 1-hour charts, 5-10 trades/day is more typical.
 Session Group 
 Session Start Hour (default: 5):  Hour (0-23 format) when trading is allowed to begin, in the timezone specified. For US futures trading in Chicago time, session typically starts at 5:00 or 6:00 PM (17:00 or 18:00) Sunday evening.
 Session End Hour (default: 17):  Hour when trading stops and no new entries are allowed. For US equity index futures, regular session ends at 4:00 PM (16:00) Central Time.
 Allow Weekend Trading (default: false):  Whether strategy can trade on Saturday/Sunday. Most futures have low volume on weekends; keeping this disabled is recommended unless you specifically trade Sunday evening open.
 Session Timezone (default: America/Chicago):  Timezone for session hour interpretation. Select your local timezone or the timezone of your instrument's primary exchange. This ensures session logic aligns with your intended trading hours.
 Prop Guards Group 
 Trailing Drawdown Guard (default: false):  Enables prop-firm-style trailing maximum drawdown. When enabled, if equity drops below (Peak Equity - Trailing DD Amount), all trading halts for the remainder of the backtest/live session. This simulates rules used by funded trader programs where exceeding trailing drawdown terminates the account.
 Trailing DD Amount (default: $2,500):  Dollar amount of drawdown allowed from equity peak. If your equity reaches $55,000, the trailing stop sets at $52,500. If equity then drops to $52,499, the guard triggers and trading ceases.
 Execution Kernel Group 
 Entry Mode (default: StopBreakout):  
- StopBreakout: Places stop orders above/below signal bar requiring price confirmation
- LimitPullback: Places limit orders at pullback prices seeking better fills
- MarketNextOpen: Executes immediately at market on next bar
 Limit Offset (default: 0.5x ATR):  For LimitPullback mode, how far below/above current price to place the limit order. Smaller values (0.3-0.5) seek minor pullbacks. Larger values (0.8-1.2) wait for deeper retracements but may miss trades.
 Entry TTL (default: 6 bars, 0=off):  Bars an entry order remains pending before cancelling. Shorter values (3-4) keep signals fresh. Longer values (8-12) allow more time for fills but risk executing stale signals. Set to 0 to disable TTL (orders remain active indefinitely until filled or opposite signal).
 Exits Group 
 Stop Loss (default: 1.25x ATR):  Base stop distance as a multiple of the 14-period ATR. This is your primary risk control parameter and directly impacts your stop-out rate. Lower values (0.8-1.0) create tighter stops that reduce risk per trade but may get stopped out prematurely in volatile conditions—expect stop-out rates above 65% (red zone). Higher values (1.5-2.5) give trades more room to breathe but increase risk per contract—expect stop-out rates below 30% (green zone). The system applies additional volatility regime adjustments on top of this base: ×1.2 in high volatility environments (stops widen automatically), ×0.8 in low volatility (stops tighten), ×1.0 in normal conditions. For scalping on lower timeframes, use 0.8-1.2. For swing trading on higher timeframes, use 1.5-2.5. Monitor the Stop-Out Rate metric in the dashboard and adjust this parameter to keep it in the healthy 30-65% orange zone.
 Move to Breakeven at (default: 1.0R):  When profit reaches this multiple of initial risk, stop moves to breakeven. 1.0R means after price moves in your favor by the distance you risked, you're protected at entry price. Lower values (0.5-0.8R) lock in breakeven faster. Higher values (1.5-2.0R) allow more room before protection.
 Start Trailing at (default: 1.2R):  When profit reaches this multiple, the fixed stop transitions to a dynamic trailing stop. This should be greater than the BE trigger. Values typically range 1.0-2.0R depending on how much profit you want secured before trailing activates.
 Trail Offset (default: 1.0R):  How far behind price the trailing stop follows. Tighter offsets (0.5-0.8R) protect profit more aggressively but may exit prematurely. Wider offsets (1.5-2.5R) allow more room for profit to run but risk giving back more on reversals.
 Trail Step (default: 1.5R):  How far price must move in profitable direction before the stop advances. Smaller steps (0.5-1.0R) move the stop more frequently, tightening protection continuously. Larger steps (2.0-3.0R) move the stop less often, giving trades more breathing room.
 Max Bars In Trade (default: 0=off):  Maximum bars allowed in a position before forced exit. This prevents trades from "going stale" during periods of no meaningful price action. For 5-minute charts, 50-100 bars (4-8 hours) is reasonable. For daily charts, 5-10 bars (1-2 weeks) is typical. Set to 0 to disable.
 Flatten near Session End (default: true):  Whether to automatically close all positions as session end approaches. Recommended to avoid carrying positions into off-hours with low liquidity.
 Minutes before end (default: 5):  How many minutes before session end to flatten. 5-15 minutes provides buffer for order execution before the session boundary.
 Visual Effects Configuration Group 
 Dashboard Size (default: Normal):  Controls information density in the dashboard. Small shows only critical metrics (excludes stop-out rate). Normal shows comprehensive data including stop-out rate. Large shows all available metrics including weights, session info, and volume analysis. Larger sizes consume more screen space but provide complete visibility.
 Show Quantum Field (default: true):  Displays animated grid pattern on the chart indicating market state. Disable if you prefer cleaner charts or experience performance issues on lower-end hardware.
 Show Wick Pressure Lines (default: true):  Draws dynamic lines from bars with extreme wicks, indicating potential support/resistance or liquidity absorption zones. Disable for simpler visualization.
 Show Morphism Energy Beams (default: true):  Displays directional beams showing momentum energy flow. Beams intensify during strong trends. Disable if you find this visually distracting.
 Show Order Flow Clouds (default: true):  Draws translucent boxes representing volume flow bullish/bearish bias. Disable for cleaner price action visibility.
 Show Fractal Grid (default: true):  Displays multi-timeframe support/resistance levels based on fractal price structure at 10/20/30/40/50 bar periods. Disable if you only want to see primary pivot levels.
 Glow Intensity (default: 4):  Controls the brightness and thickness of visual effects. Lower values (1-2) for subtle visualization. Higher values (7-10) for maximum visibility but potentially cluttered charts.
 Color Theme (default: Cyber):  Visual color scheme. Cyber uses cyan/magenta futuristic colors. Quantum uses aqua/purple. Matrix uses green/red terminal style. Aurora uses pastel pink/purple gradient. Choose based on personal preference and monitor calibration.
 Show Watermark (default: true):  Displays animated watermark at bottom of chart with creator credit and current P&L. Disable if you want completely clean charts or need screen space.
 Performance Characteristics and Best Use Cases 
 Optimal Conditions 
This strategy performs best in markets exhibiting:
 Trending phases with periodic pullbacks:  The combination of momentum and structure components excels when price establishes directional bias but provides retracement opportunities for entries. Markets with 60-70% trending bars and 30-40% consolidation produce the highest win rates.
 Medium to high volatility:  The ATR-based stop sizing and dynamic risk adjustment require sufficient price movement to generate meaningful profit relative to risk. Instruments with 2-4% daily ATR relative to price work well. Extremely low volatility (<1% daily ATR) generates too many scratch trades.
 Clear volume patterns:  The VPT volume component adds significant edge when volume expansions align with directional moves. Instruments and timeframes where volume data reflects actual transaction flow (versus tick volume proxies) perform better.
 Regular session structure:  Futures markets with defined opening and closing hours, consistent liquidity throughout the session, and clear overnight/day session separation allow the session controls and time-based failsafes to function optimally.
 Sufficient liquidity for stop execution:  The stop breakout entry mode requires that stop orders can fill without significant slippage. Highly liquid contracts work better than illiquid instruments where stop orders may face adverse fills.
 Suboptimal Conditions 
The strategy may struggle with:
 Extreme chop with no directional persistence:  When ADX remains below 15 for extended periods and price oscillates rapidly without establishing trends, the momentum component generates conflicting signals. Win rate typically drops below 40% in these conditions, triggering the adaptive system to increase minimum score thresholds until conditions improve. Stop-out rates may also spike into the red zone.
 Gap-heavy instruments:  Markets with frequent overnight gaps disrupt the continuous price assumptions underlying ATR stops and EMA-based structure analysis. Gaps can also cause stop orders to fill at prices far from intended levels, distorting stop-out rate metrics.
 Very low timeframes with excessive noise:  On 1-minute or tick charts, the signal components react to micro-structure noise rather than meaningful price swings. The strategy works best on 5-minute through daily timeframes where price movements reflect actual order flow shifts.
 Extended low-volatility compression:  During historically low volatility periods, profit targets become difficult to reach before mean-reversion occurs. The trail offset, even when set to minimum, may be too wide for the compressed price environment. Stop-out rates may drop to green zone indicating stops should be tightened.
 Parabolic moves or climactic exhaustion:  Vertical price advances or selloffs where price moves multiple ATRs in single bars can trigger momentum signals at exhaustion points. The structure and reversal components attempt to filter these, but extreme moves may override normal logic.
The adaptive learning system naturally reduces signal frequency and position sizing during unfavorable conditions. If you observe multiple consecutive days with zero trades and "FILTERS ACTIVE" status, this indicates the strategy has self-adjusted to avoid poor conditions rather than forcing trades.
 Instrument Recommendations 
 Emini Index Futures (ES, MES, NQ, MNQ, YM, RTY):  Excellent fit. High liquidity, clear volatility patterns, strong volume signals, defined session structure. These instruments have been extensively tested and the universal detection handles all contract specifications automatically.
 Micro Index Futures (MES, MNQ, M2K, MYM):  Excellent fit for smaller accounts. Same market characteristics as the standard eminis but with reduced contract sizes allowing proper risk management on accounts below $50,000.
 Energy Futures (CL, NG, RB, HO):  Good to mixed fit. Crude oil (CL) works well due to strong trends and reasonable volatility. Natural gas (NG) can be extremely volatile—consider reducing Base Risk to 0.3-0.4% and increasing Stop Loss ATR multiplier to 1.8-2.2 for NG. The strategy automatically detects the $10/tick value for CL and adjusts position sizing accordingly.
 Metal Futures (GC, SI, HG, PL):  Good fit. Gold (GC) and silver (SI) exhibit clear trending behavior and work well with the momentum/structure components. The strategy automatically handles the different point values ($100/point for gold, $5,000/point for silver).
 Agricultural Futures (ZC, ZS, ZW, ZL):  Good fit. Grain futures often trend strongly during seasonal periods. The strategy handles the unique tick sizes (1/4 cent increments) and point values ($50/point for corn/wheat, $60/point for soybeans) automatically.
 Treasury Futures (ZB, ZN, ZF, ZT):  Good fit for trending rates environments. The strategy automatically handles the fractional tick sizing (32nds for ZB/ZN, halves of 32nds for ZF/ZT) through the universal detection system.
 Currency Futures (6E, 6J, 6B, 6A, 6C):  Good fit. Major currency pairs exhibit smooth trending behavior. The strategy automatically detects point values which vary significantly ($12.50/tick for 6E, $12.50/tick for 6J, $6.25/tick for 6B).
 Cryptocurrency Futures (BTC, ETH, MBT, MET):  Mixed fit. These markets have extreme volatility requiring parameter adjustment. Increase Base Risk to 0.8-1.2% and Stop Loss ATR multiplier to 2.0-3.0 to account for wider stop distances. Enable 24-hour trading and weekend trading as these markets have no traditional sessions.
The universal futures compatibility means you can apply this strategy to any of these markets without code modification—simply open the chart of your desired contract and the strategy will automatically configure itself to that instrument's specifications.
 Important Disclaimers and Realistic Expectations 
This is a sophisticated trading strategy that combines multiple analytical methods within an adaptive framework designed for active traders who will monitor performance and market conditions. It is not a "set and forget" fully automated system, nor should it be treated as a guaranteed profit generator.
 Backtesting Realism and Limitations 
The strategy includes realistic trading costs and execution assumptions:
- Commission: $0.62 per contract per side (accurate for many retail futures brokers)
- Slippage: 1 tick per entry and exit (conservative estimate for liquid futures)
- Position sizing: Realistic risk percentages and maximum contract limits based on account size
- No repainting: All calculations use confirmed bar data only—signals do not change retroactively
However, backtesting cannot fully capture live trading reality:
- Order fill delays: In live trading, stop and limit orders may not fill instantly at the exact tick shown in backtest
- Volatile periods: During high volatility or low liquidity (news events, rollover days, pre-holidays), slippage may exceed the 1-tick assumption significantly
- Gap risk: The backtest assumes stops fill at stop price, but gaps can cause fills far beyond intended exit levels
- Psychological factors: Seeing actual capital at risk creates emotional pressures not present in backtesting, potentially leading to premature manual intervention
The strategy's backtest results should be viewed as best-case scenarios. Real trading will typically produce 10-30% lower returns than backtest due to the above factors.
 Risk Warnings 
 All trading involves substantial risk of loss.  The adaptive learning system can improve parameter selection over time, but it cannot predict future price movements or guarantee profitable performance. Past wins do not ensure future wins.
 Losing streaks are inevitable.  Even with a 60% win rate, you will encounter sequences of 5, 6, or more consecutive losses due to normal probability distributions. The strategy includes losing streak detection and automatic risk reduction, but you must have sufficient capital to survive these drawdowns.
 Market regime changes can invalidate learned patterns.  If the strategy learns from 50 trades during a trending regime, then the market shifts to a ranging regime, the adapted parameters may initially be misaligned with the new environment. The system will re-adapt, but this transition period may produce suboptimal results.
 Prop firm traders: understand your specific rules.  Every prop firm has different rules regarding maximum drawdown, daily loss limits, consistency requirements, and prohibited trading behaviors. While this strategy includes common prop guardrails, you must verify it complies with your specific firm's rules and adjust parameters accordingly.
 Never risk capital you cannot afford to lose.  This strategy can produce substantial drawdowns, especially during learning periods or market regime shifts. Only trade with speculative capital that, if lost, would not impact your financial stability.
 Recommended Usage 
 Paper trade first:  Run the strategy on a simulated account for at least 50 trades or 1 month before committing real capital. Observe how the adaptive system behaves, identify any patterns in losing trades, monitor your stop-out rate trends, and verify your understanding of the entry/exit mechanics.
 Start with minimum position sizing:  When transitioning to live trading, reduce the Base Risk parameter to 0.3-0.4% initially (vs 0.5-1.0% in testing) to reduce early impact while the system learns your live broker's execution characteristics.
 Monitor daily, but do not micromanage:  Check the dashboard daily to ensure the strategy is operating normally and risk controls have not triggered unexpectedly. Pay special attention to the Stop-Out Rate metric—if it remains in the red or green zones for multiple days, adjust your Stop Loss ATR multiplier accordingly. However, resist the urge to manually adjust adaptive weights or disable trades based on short-term performance. Allow the adaptive system at least 30 trades to establish patterns before making manual changes.
 Combine with other analysis:  While this strategy can operate standalone, professional traders typically use systematic strategies as one component of a broader approach. Consider using the strategy for trade execution while applying your own higher-timeframe analysis or fundamental view for trade filtering or sizing adjustments.
 Keep a trading journal:  Document each week's results, note market conditions (trending vs ranging, high vs low volatility), record stop-out rates and any Stop Loss ATR adjustments you made, and document any manual interventions. Over time, this journal will help you identify conditions where the strategy excels versus struggles, allowing you to selectively enable or disable trading during certain environments.
 Technical Implementation Notes 
All calculations execute on closed bars only (`calc_on_every_tick=false`) ensuring that signals and values do not repaint. Once a bar closes and a signal generates, that signal is permanent in the history.
The strategy uses fixed-quantity position sizing (`default_qty_type=strategy.fixed, default_qty_value=1`) with the actual contract quantity determined by the position sizing function and passed to the entry commands. This approach provides maximum control over risk allocation.
Order management uses Pine Script's native `strategy.entry()` and `strategy.exit()` functions with appropriate parameters for stops, limits, and trailing stops. All orders include explicit from_entry references to ensure they apply to the correct position.
The adaptive learning arrays (trade_returns, trade_directions, trade_types, trade_hours, trade_was_stopped) are maintained as circular buffers capped at PERFORMANCE_MEMORY size (default 100 trades). When a new trade closes, its data is added to the beginning of the array using `array.unshift()`, and the oldest trade is removed using `array.pop()` if capacity is exceeded. The stop-out tracking system analyzes the trade_was_stopped array to calculate the rolling percentage displayed in the dashboard.
Dashboard rendering occurs only on the confirmed bar (`barstate.isconfirmed`) to minimize computational overhead. The table is pre-created with sufficient rows for the selected dashboard size and cells are populated with current values each update.
Visual effects (fractal grid, wick pressure, morphism beams, order flow clouds, quantum field) recalculate on each bar for real-time chart updates. These are computationally intensive—if you experience chart lag, disable these visual components. The core strategy logic continues to function identically regardless of visual settings.
Timezone conversions use Pine Script's built-in timezone parameter on the `hour()`, `minute()`, and `dayofweek()` functions. This ensures session logic and daily/weekly resets occur at correct boundaries regardless of the chart's default timezone or the server's timezone.
The universal futures detection queries `syminfo.mintick` and `syminfo.pointvalue` on each strategy initialization to obtain the current instrument's specifications. These values remain constant throughout the strategy's execution on a given chart but automatically update when the strategy is applied to a different instrument.
The strategy has been tested on TradingView across timeframes from 5-minute through daily and across multiple futures instrument types including equity indices, energy, metals, agriculture, treasuries, and currencies. It functions identically on all instruments due to the percentage-based risk model and ATR-relative calculations which adapt automatically to price scale and volatility, combined with the universal futures detection system that handles contract-specific specifications.
CVD Divergence with SMA Volume Multi-period CVD Divergence Detector
### 🔹 **Full Description:**
This indicator detects bullish and bearish **CVD (Cumulative Volume Delta) divergences** using multiple periods (5, 7, 14, 21, 28).
It visualizes divergence lines directly on the chart and includes a **volume strength filter** to highlight only strong setups.
Features:
* Multi-time CVD calculation (Periodic or EMA mode)
* Automatic divergence detection
* Adjustable volume-based filtering
* Visual price lines and divergence labels
* Built-in alert system for new divergences
Works best on **1m–1h timeframes** for scalping and intraday analysis.
Smart Divergence Engine [ChartNation]Precision-grade divergence signals—confirmed on close, never repainted. 
 Smart Divergence Engine  locks onto real bullish/bearish divergences using pivot-confirmed RSI math and prints the signal right at bar close, so entries are clean and non-repainting. Its panel and price-overlay stay perfectly in sync, with candle-anchored plots that don’t drift when you zoom. A volatility “shark-fin” filter cuts noise, while adjustable pivot sensitivity lets you tune frequency for your market and timeframe. 
Get  instant BUY/SELL  alerts only when momentum and price truly disagree—delivering accurate, decisive trades without second-guessing.
Smart Moving Average Dynamics [Chart Nation]Smart Moving Average Dynamics (SMAD)  transforms a basic moving average into a precision trading engine. It detects true momentum shifts through advanced normalization (Z-Score, ATR, Percent Rank), confirms trend direction using MA slope, and overlays live context from volume and volatility.
 The result:  cleaner confirmations, earlier reversals, and less noise in your signals — helping traders pinpoint high-probability entries and exits across any market or timeframe.
 Key Features: 
 Adaptive normalization for accurate momentum reading
Built-in volume & volatility sentiment gauge
Smart filtered reversal signals
Dynamic “rail” levels for exhaustion detection
Works on all assets and timeframes
TraderDemircan (Triz Global) Stochastic RSI - WaveTrend v1.1Detects buy/sell signals when WaveTrend, Stochastic RSI K-line, and D-line converge within a defined distance, confirm momentum direction, and align with overbought/oversold zones.
TENOMAX V15 OSC (by 3dots)A simple scalping tool ...
By using crsi and moving average and calculated divergences using rsi and macd and a powerful vwap calculation , now it is easy to decide where we can enter a trade.
RSI-ADX Dual Bot (v1.1) — Long/Short RSI & ADX TUNG BUGI JAPANRSI-ADX Dual Bot v1.1 is a trading strategy combining the power of RSI and ADX
to determine Long/Short points when the market is trending strongly. Automatically close orders when RSI reverses
Retested on XAUUSD H1 with PF > 1.7 and drawdown < 10%.
Technical Checklist_DTBasic Checklist table for bullish condition checks for ADX, RSI, VWAP , CPR, Supertrend
Ultimate Oscillator (ULTOSC)The Ultimate Oscillator (ULTOSC) is a technical momentum indicator developed by Larry Williams that combines three different time periods to reduce the volatility and false signals common in single-period oscillators. By using a weighted average of three Stochastic-like calculations across short, medium, and long-term periods, the Ultimate Oscillator provides a more comprehensive view of market momentum while maintaining sensitivity to price changes.
The indicator addresses the common problem of oscillators being either too sensitive (generating many false signals) or too slow (missing opportunities). By incorporating multiple timeframes with decreasing weights for longer periods, ULTOSC attempts to capture both short-term momentum shifts and longer-term trend strength, making it particularly valuable for identifying divergences and potential reversal points.
## Core Concepts
* **Multi-timeframe analysis:** Combines three different periods (typically 7, 14, 28) to capture various momentum cycles
* **Weighted averaging:** Assigns higher weights to shorter periods for responsiveness while including longer periods for stability
* **Buying pressure focus:** Measures the relationship between closing price and the true range rather than just high-low range
* **Divergence detection:** Particularly effective at identifying momentum divergences that precede price reversals
* **Normalized scale:** Oscillates between 0 and 100, with clear overbought/oversold levels
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Fast Period | 7 | Short-term momentum calculation | Lower (5-6) for more sensitivity, higher (9-12) for smoother signals |
| Medium Period | 14 | Medium-term momentum calculation | Adjust based on typical swing duration in the market |
| Slow Period | 28 | Long-term momentum calculation | Higher values (35-42) for longer-term position trading |
| Fast Weight | 4.0 | Weight applied to fast period | Higher weight increases short-term sensitivity |
| Medium Weight | 2.0 | Weight applied to medium period | Adjust to balance medium-term influence |
| Slow Weight | 1.0 | Weight applied to slow period | Usually kept at 1.0 as the baseline weight |
**Pro Tip:** The classic 7/14/28 periods with 4/2/1 weights work well for most markets, but consider using 5/10/20 with adjusted weights for faster markets or 14/28/56 for longer-term analysis.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Ultimate Oscillator calculates three separate "buying pressure" ratios using different time periods, then combines them using weighted averaging. Buying pressure is defined as the close minus the true low, divided by the true range.
**Technical formula:**
```
BP = Close - Min(Low, Previous Close)
TR = Max(High, Previous Close) - Min(Low, Previous Close)
BP_Sum_Fast = Sum(BP, Fast Period)
TR_Sum_Fast = Sum(TR, Fast Period)
Raw_Fast = 100 × (BP_Sum_Fast / TR_Sum_Fast)
BP_Sum_Medium = Sum(BP, Medium Period)
TR_Sum_Medium = Sum(TR, Medium Period)
Raw_Medium = 100 × (BP_Sum_Medium / TR_Sum_Medium)
BP_Sum_Slow = Sum(BP, Slow Period)
TR_Sum_Slow = Sum(TR, Slow Period)
Raw_Slow = 100 × (BP_Sum_Slow / TR_Sum_Slow)
ULTOSC = 100 ×   / (Fast_Weight + Medium_Weight + Slow_Weight)
```
Where:
- BP = Buying Pressure
- TR = True Range
- Fast Period = 7, Medium Period = 14, Slow Period = 28 (defaults)
- Fast Weight = 4, Medium Weight = 2, Slow Weight = 1 (defaults)
> 🔍 **Technical Note:** The implementation uses efficient circular buffers for all three period calculations, maintaining O(1) time complexity per bar. The algorithm properly handles true range calculations including gaps and ensures accurate buying pressure measurements across all timeframes.
## Interpretation Details
ULTOSC provides several analytical perspectives:
* **Overbought/Oversold conditions:** Values above 70 suggest overbought conditions, below 30 suggest oversold conditions
* **Momentum direction:** Rising ULTOSC indicates increasing buying pressure, falling indicates increasing selling pressure
* **Divergence analysis:** Divergences between ULTOSC and price often precede significant reversals
* **Trend confirmation:** ULTOSC direction can confirm or question the prevailing price trend
* **Signal quality:** Extreme readings (>80 or <20) indicate strong momentum that may be unsustainable
* **Multiple timeframe consensus:** When all three underlying periods agree, signals are typically more reliable
## Trading Applications
**Primary Uses:**
- **Divergence trading:** Identify when momentum diverges from price for reversal signals
- **Overbought/oversold identification:** Find potential entry/exit points at extreme levels
- **Trend confirmation:** Validate breakouts and trend continuations
- **Momentum analysis:** Assess the strength of current price movements
**Advanced Strategies:**
- **Multi-divergence confirmation:** Look for divergences across multiple timeframes
- **Momentum breakouts:** Trade when ULTOSC breaks above/below key levels with volume
- **Swing trading entries:** Use oversold/overbought levels for swing position entries
- **Trend strength assessment:** Evaluate trend quality using momentum consistency
## Signal Combinations
**Strong Bullish Signals:**
- ULTOSC rises from oversold territory (<30) with positive price divergence
- ULTOSC breaks above 50 after forming a base near 30
- All three underlying periods show increasing buying pressure
**Strong Bearish Signals:**
- ULTOSC falls from overbought territory (>70) with negative price divergence
- ULTOSC breaks below 50 after forming a top near 70
- All three underlying periods show decreasing buying pressure
**Divergence Signals:**
- **Bullish divergence:** Price makes lower lows while ULTOSC makes higher lows
- **Bearish divergence:** Price makes higher highs while ULTOSC makes lower highs
- **Hidden bullish divergence:** Price makes higher lows while ULTOSC makes lower lows (trend continuation)
- **Hidden bearish divergence:** Price makes lower highs while ULTOSC makes higher highs (trend continuation)
## Comparison with Related Oscillators
| Indicator | Periods | Focus | Best Use Case |
|-----------|---------|-------|---------------|
| **Ultimate Oscillator** | 3 periods | Buying pressure | Divergence detection |
| **Stochastic** | 1-2 periods | Price position | Overbought/oversold |
| **RSI** | 1 period | Price momentum | Momentum analysis |
| **Williams %R** | 1 period | Price position | Short-term signals |
## Advanced Configurations
**Fast Trading Setup:**
- Fast: 5, Medium: 10, Slow: 20
- Weights: 4/2/1, Thresholds: 75/25
**Standard Setup:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 4/2/1, Thresholds: 70/30
**Conservative Setup:**
- Fast: 14, Medium: 28, Slow: 56
- Weights: 3/2/1, Thresholds: 65/35
**Divergence Focused:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 2/2/2, Thresholds: 70/30
## Market-Specific Adjustments
**Volatile Markets:**
- Use longer periods (10/20/40) to reduce noise
- Consider higher threshold levels (75/25)
- Focus on extreme readings for signal quality
**Trending Markets:**
- Emphasize divergence analysis over absolute levels
- Look for momentum confirmation rather than reversal signals
- Use hidden divergences for trend continuation
**Range-Bound Markets:**
- Standard overbought/oversold levels work well
- Trade reversals from extreme levels
- Combine with support/resistance analysis
## Limitations and Considerations
* **Lagging component:** Contains inherent lag due to multiple moving average calculations
* **Complex calculation:** More computationally intensive than single-period oscillators
* **Parameter sensitivity:** Performance varies significantly with different period/weight combinations
* **Market dependency:** Most effective in trending markets with clear momentum patterns
* **False divergences:** Not all divergences lead to significant price reversals
* **Whipsaw potential:** Can generate conflicting signals in choppy markets
## Best Practices
**Effective Usage:**
- Focus on divergences rather than absolute overbought/oversold levels
- Combine with trend analysis for context
- Use multiple timeframe analysis for confirmation
- Pay attention to the speed of momentum changes
**Common Mistakes:**
- Over-relying on overbought/oversold levels in strong trends
- Ignoring the underlying trend direction
- Using inappropriate period settings for the market being analyzed
- Trading every divergence without additional confirmation
**Signal Enhancement:**
- Combine with volume analysis for confirmation
- Use price action context (support/resistance levels)
- Consider market volatility when setting thresholds
- Look for convergence across multiple momentum indicators
## Historical Context and Development
The Ultimate Oscillator was developed by Larry Williams and introduced in his 1985 article "The Ultimate Oscillator" in Technical Analysis of Stocks and Commodities magazine. Williams designed it to address the limitations of single-period oscillators by:
- Reducing false signals through multi-timeframe analysis
- Maintaining sensitivity to short-term momentum changes
- Providing more reliable divergence signals
- Creating a more robust momentum measurement tool
The indicator has become a standard tool in technical analysis, particularly valued for its divergence detection capabilities and its balanced approach to momentum measurement.
## References
* Williams, L. R. (1985). The Ultimate Oscillator. Technical Analysis of Stocks and Commodities, 3(4).
* Williams, L. R. (1999). Long-Term Secrets to Short-Term Trading. Wiley Trading.
Easy Read Short‑Term EMA CrossoverThis TradingView panel shows a multi-indicator setup for analyzing the S&P 500 Index (SPX):
Main chart (top): displays price candles with two Exponential Moving Averages (EMA 8 and 21). When the short-term EMA (blue) crosses above the long-term EMA (red), it gives a Buy signal; when it crosses below, a Sell signal appears — helping identify short-term trend shifts.
Middle panel: shows the Easy-Read RSI, highlighting overbought (OB) and oversold (OS) zones. When RSI moves above 70 it signals potential weakness (sell), and below 30 suggests a rebound zone (buy).
Bottom panel: plots the Easy-Read MACD, which tracks momentum by comparing short- and long-term moving averages. When the MACD line crosses above the Signal line, it indicates bullish momentum; crossing below suggests bearish momentum.
Together, these three indicators provide a layered view of trend, momentum, and potential entry/exit points.
RSI MT5-Style RSI Zones (20/30/70/80) with Signals & Alerts
Description (English first)
What it does
This script reproduces an MT5-style RSI with four-level zones (20/30/70/80) to better distinguish early/late overbought-oversold conditions. It highlights zone transitions, plots optional background shading, and triggers entry/exit alerts on precise crossings.
How it works (high-level logic)
Core is Wilder’s RSI on close (length = ).
Two oversold bands at 20 and 30; two overbought bands at 70 and 80.
Optional smoothing (), and MTF confirmation (optional) compares current RSI vs a higher timeframe RSI.
Signals:
Long setup: RSI crosses above 20 (early) or 30 (conservative); confirmation if higher-TF RSI is rising.
Take-profit / exit: RSI fails to hold above 70 or crosses below 70 after being >80.
Short setup: mirror logic with 70/80 → 30/20.
Inputs
RSI Length (<14>), Source (close)
Upper Bands (70, 80), Lower Bands (30, 20)
Smoothing ( on RSI, optional)
Higher Timeframe (), Confirm with HTF (on/off)
Background Zones (on/off), Alerts (on/off)
How to use
Choose your market/timeframe. For FX/indices, M5–H1 works well; for swing, H1–H4.
Pick your aggressiveness: use 20/80 for early reversals, 30/70 for conservative trend pullbacks.
With MTF confirmation on, prioritize entries aligned with the higher timeframe RSI slope.
Combine with structure (S/R) or a simple MA filter for trend direction.
Originality & usefulness
Unlike generic RSI scripts, this version provides dual-zone logic (20/30/70/80) with clear visual states, optional HTF confirmation, and ready-made alerts designed to match MetaTrader-like RSI workflows. It is not a direct clone of public open-source scripts; zone handling and alert conditions are purpose-built for timing pullbacks vs. extremes.
Best markets & limitations
Works on FX, gold (XAUUSD), and indices (US30/NAS100).
In strong trends, overbought/oversold can persist—use bands as context, not standalone signals.
Spikes around news can cause false triggers—consider widening bands or disabling trades near events.
Alerts included
RSI Crosses Above 20, RSI Crosses Above 30
RSI Crosses Below 70, RSI Crosses Below 80
MTF Confirmed Long/Short (optional)
User interface translations (if your UI is in Spanish)
RSI Length → Periodo RSI
Upper Bands → Bandas Superiores
Lower Bands → Bandas Inferiores
Smoothing → Suavizado
Higher Timeframe → Marco Temporal Superior
Confirm with HTF → Confirmar con MTS
Background Zones → Zonas de Fondo
Alerts → Alertas
Disclaimer
This tool is for educational purposes. Not financial advice.
Buying/Selling PressureBuying/Selling Pressure - Volume-Based Market Sentiment 
Buying/Selling Pressure identifies market dominance by separating volume into buying and selling components. The indicator uses Volume ATR normalization to create a universal pressure oscillator that works consistently across all markets and timeframes.
 What is Buying/Selling Pressure? 
This indicator answers a fundamental question: Are buyers or sellers in control? By analyzing how volume distributes within each bar, it calculates cumulative buying and selling pressure, then normalizes the result using Volume ATR for cross-market comparability.
 Formula:    × 100
Where Delta = Buying Volume - Selling Volume
 Calculation Methods 
 Money Flow (Recommended): 
Volume weighted by close position in bar range. Close near high = buying pressure, close near low = selling pressure.
Formula:   / (high - low)
 Simple Delta: 
Basic approach where bullish bars = 100% buying, bearish bars = 100% selling.
 Weighted Delta: 
Volume weighted by body size relative to total range, focusing on candle strength.
 Key Features 
 
 Volume ATR Normalization:  Adapts to volume volatility for consistent readings across assets
 Cumulative Delta:  Tracks net buying/selling pressure over time (similar to OBV)
 Signal Line:  EMA smoothing for trend identification and crossover signals
 Zero Line:  Clear visual separation between buyer and seller dominance
 Color-Coded Display:  Green area = buyers control, red area = sellers control
 
 Interpretation 
 Above Zero:  Buyers dominating - cumulative buying pressure exceeds selling
 Below Zero:  Sellers dominating - cumulative selling pressure exceeds buying
 Cross Signal Line:  Momentum shift - pressure trend changing direction
 Increasing Magnitude:  Strengthening pressure in current direction
 Decreasing Magnitude:  Weakening pressure, potential reversal
 Volume vs Pressure 
High volume with low pressure indicates balanced battle between buyers and sellers. High pressure with high volume confirms strong directional conviction. This separation provides insights beyond traditional volume analysis.
 Best Practices 
 
 Use with price action for confirmation
 Divergences signal potential reversals (price makes new high/low but pressure doesn't)
 Large volume with near-zero pressure = indecision, breakout preparation
 Signal line crossovers provide momentum change signals
 Extreme readings suggest potential exhaustion
 
 Settings 
 
 Calculation Method:  Choose Money Flow, Simple Delta, or Weighted Delta
 EMA Length:  Period for cumulative delta smoothing (default: 21)
 Signal Line:  Optional EMA of oscillator for crossover signals (default: 9)
 
Buying/Selling Pressure transforms volume analysis into actionable market sentiment, revealing whether buyers or sellers control price action beneath surface volatility.
 This indicator is designed for educational and analytical purposes. Past performance does not guarantee future results. Always conduct thorough research and consider consulting with financial professionals before making investment decisions. 
Wave Conflict DetectorWave Conflict Detector 
 Wave Conflict Detector: Identifying Pivot Conditions Through Wave Interference Analysis 
Wave Conflict Detector applies wave interference principles from physics to dual-EMA analysis, identifying potential pivot conditions by measuring phase relationships and amplitude states between two moving average waves. Unlike traditional EMA crossover systems that signal on wave intersection, this indicator measures the directional alignment (phase) and interaction strength (interference amplitude) between wave states to identify conditions where wave mechanics suggest potential reversal zones.
The indicator combines two analytical components: velocity-based phase difference calculation that measures whether waves are moving in the same or opposite directions, and normalized interference amplitude that quantifies the degree of wave reinforcement or cancellation. This creates a regime-classification system with visual feedback showing when waves are aligned (constructive state) versus opposed (destructive state).
 What Makes This Approach Different 
 Phase Relationship Measurement 
The core analytical method is extracting phase alignment from wave velocities rather than simply measuring EMA separation. The system calculates the first derivative (bar-to-bar change) of each EMA, creating velocity measurements: v₁ = ψ₁ - ψ₁  and v₂ = ψ₂ - ψ₂ . These velocities are combined through normalized correlation: Φ = (v₁ × v₂) / |v|², producing an alignment value ranging from -1 (perfect opposition) to +1 (perfect alignment).
This alignment value is smoothed using EMA and converted to angular degrees: Δφ = (1 - Φ) × 90°, creating a phase difference measurement from 0° to 180°. This quantifies how much the waves are "fighting" each other directionally, independent of their separation distance. Two EMAs can be far apart yet moving in harmony (low phase difference), or close together yet moving in opposition (high phase difference).
This directional correlation approach differs from standard dual-EMA analysis by focusing on velocity alignment rather than positional crossovers.
 Interference Amplitude Calculation 
The interference formula implements wave superposition principles: I = (|ψ₁ + ψ₂|² - |ψ₁ - ψ₂|²) × Gain, which mathematically simplifies to I = 4 × ψ₁ × ψ₂ × Gain. This measures the product of both waves—when both are positive and large, interference is maximally constructive; when they have opposite signs or differing magnitudes, interference weakens.
The raw interference value is then normalized using adaptive statistical bounds calculated over a rolling window (default 100 bars). The system computes mean (μ) and standard deviation (σ) of raw interference, then applies bounds of μ ± 2σ, and normalizes to a 0-1 range. This creates a scale-invariant measurement that adapts automatically to different instruments and volatility regimes without requiring manual recalibration.
The combination of phase measurement and normalized amplitude creates a two-dimensional state space for classifying market conditions.
 Dual-Mode Detection Architecture 
The system offers two detection approaches that can be selected based on market conditions:
 Interference Mode:  Detects pivot conditions when normalized interference amplitude forms local peaks or troughs (current bar is higher/lower than both adjacent bars) AND exceeds the configured threshold. This identifies extremes in wave interaction strength.
 Phase Mode:  Detects pivot conditions when phase alignment reverses (crosses from positive to negative or vice versa) AND absolute phase difference exceeds the threshold. This identifies directional relationship changes between waves.
Both modes require price structure confirmation (traditional pivot high/low patterns) and minimum bar spacing to prevent over-signaling. This architecture allows traders to match detection sensitivity to market character—interference mode for amplitude-driven markets, phase mode for directional trend shifts.
 Multi-Layer Visual System 
The visualization approach uses hierarchical layers to display wave state information:
 Foundation Layer:  The two EMA waves (ψ₁ and ψ₂) plotted directly on the price chart, showing the underlying wave states being analyzed.
 Background Layer:  Color-coded zones showing regime state—green tint when phase alignment is positive (constructive interference), red tint when phase alignment is negative below -0.3 (destructive interference).
 Dynamic Ribbon:  A band centered on the wave average with width proportional to |ψ₁ - ψ₂| × (0.5 + interference_norm). This creates an adaptive channel that expands with interference strength and contracts during low-energy states.
 Phase Field:  Multi-frequency harmonic oscillations generated using three phase accumulators driven by interference amplitude, phase alignment, and accumulated phase rotation. Multiple sine-wave layers create visual texture that becomes erratic during wave conflict conditions and smooth during aligned states.
 Particle System:  Floating symbols whose density is proportional to interference amplitude, creating a visual intensity indicator.
Each visual component displays non-redundant information about the wave state system.
 Core Calculation Methodology 
 Wave State Generation 
Two exponential moving averages are calculated using configurable lengths (default 8 and 21 bars):
- ψ₁ = EMA(close, fastLen) — fast wave component
- ψ₂ = EMA(close, slowLen) — slow wave component
These serve as the base wave functions for all subsequent analysis.
 Velocity Extraction 
First derivatives are computed as simple bar-to-bar differences:
- psi1_velocity = ψ₁ - ψ₁ 
- psi2_velocity = ψ₂ - ψ₂ 
These represent the "motion" of each wave through price-time space.
 Phase Alignment Calculation 
The velocity product and magnitude are calculated:
- velocity_product = v₁ × v₂
- velocity_magnitude = √(v₁² + v₂²)
Phase alignment is computed as:
- phase_alignment = velocity_product / (velocity_magnitude²)
This is smoothed using EMA of configurable length (default 5) and converted to degrees:
- phase_degrees = (1 - phase_alignment_smooth) × 90
 Interference Amplitude Processing 
Raw interference is calculated:
- interference_raw = (constructive_amplitude - destructive_amplitude) × gain
- where constructive_amplitude = (ψ₁ + ψ₂)²
- and destructive_amplitude = (ψ₁ - ψ₂)²
Statistical normalization is applied:
- interference_mean = SMA(interference_raw, normalizationLen)
- interference_std = StdDev(interference_raw, normalizationLen)
- upper_bound = mean + 2 × std
- lower_bound = mean - 2 × std
- interference_norm = (interference_raw - lower_bound) / (upper_bound - lower_bound), clamped to  
 State Classification 
Three regime states are identified:
- Constructive: phase_alignment_smooth > 0 (waves moving in same direction)
- Destructive: phase_alignment_smooth < -0.3 (waves moving in opposite directions)
- Neutral: phase_alignment between -0.3 and 0 (weak directional correlation)
 Pivot Detection Logic 
In Interference Mode:
- High pivots: interference_norm  > interference_norm  AND interference_norm  > interference_norm  AND interference_norm  > threshold AND price forms pivot high AND spacing requirement met
- Low pivots: interference_norm shows local trough using opposite conditions
In Phase Mode:
- Pivots: phase alignment reverses sign AND absolute phase_degrees > threshold AND price forms pivot high/low AND spacing requirement met
All conditions must be true for a signal to generate.
 Dashboard Metrics System 
The dashboard displays real-time calculations:
- I (Interference): Normalized amplitude shown as bar gauge and percentage
- Δφ (Phase): Phase difference shown as bar gauge and degrees  
- ψ₁ and ψ₂: Current wave values in price units
- Wave Separation: |ψ₁ - ψ₂| with directional indicator
- STATE: Current regime classification (CONSTRUCTIVE/DESTRUCTIVE/NEUTRAL)
- PIVOT Probability: Composite score calculated as interference_norm × (phase_degrees/180) × 100
The interference matrix shows historical heatmap data across four metrics (interference amplitude, phase difference, constructive flags, destructive flags) over the configurable number of bars.
 How to Use This Indicator 
 Initial Configuration 
Apply the indicator to your chart with default settings. The fast wave length (default 8) should be adjusted to match short-term price swings for your instrument and timeframe. The slow wave length (default 21) should be 2-4 times the fast length to create adequate wave separation. Enable the dashboard (recommended position: top right) to monitor regime state and metrics in real-time.
 Signal Interpretation 
 High Pivot Marker (▼ Red Triangle):  Appears above price bars when a bearish pivot condition is detected. This indicates that price formed a swing high, the selected detection criteria were met (interference peak or phase reversal depending on mode), threshold requirements were satisfied, and the minimum spacing filter passed. This represents a potential reversal zone where wave mechanics suggest downward directional change conditions.
 Low Pivot Marker (▲ Green Triangle):  Appears below price bars when a bullish pivot condition is detected. This indicates that price formed a swing low and all detection criteria aligned. This represents a potential reversal zone where wave mechanics suggest upward directional change conditions.
 Dashboard STATE Reading 
The STATE field shows current wave relationship:
- "🟢 CONSTRUCTIVE": Waves are moving in the same direction (phase alignment positive). This suggests trend continuation conditions where waves are reinforcing each other.
- "🔴 DESTRUCTIVE": Waves are moving in opposite directions (phase alignment below -0.3). This suggests reversal-prone conditions where waves are conflicting.
- "🟡 NEUTRAL": Weak directional correlation between waves. This suggests ranging or transitional conditions.
Use STATE for regime awareness rather than specific entry signals.
 Interference and Phase Metrics 
Monitor the I (Interference) percentage:
- Above 70%: High amplitude state, significant wave interaction
- 40-70%: Moderate amplitude state  
- Below 40%: Low amplitude state, weak interaction
Monitor the Δφ (Phase) degrees:
- Above 120°: Significant wave opposition (destructive conditions)
- 60-120°: Transitional phase relationship
- Below 60°: Wave alignment (constructive conditions)
The PIVOT probability metric combines both: high values (>70%) indicate conditions where both amplitude and phase suggest elevated pivot formation potential.
 Trading Workflow Example 
 Step 1 - Regime Check:  Observe dashboard STATE to understand current wave relationship. CONSTRUCTIVE states favor trend-following approaches, DESTRUCTIVE states suggest reversal-prone conditions.
 Step 2 - Metric Monitoring:  Watch I% and Δφ values. Rising interference with high phase difference indicates building wave conflict.
 Step 3 - Visual Confirmation:  Observe amplitude ribbon width (expanding = active state) and phase field texture (chaotic = conflict conditions, smooth = aligned conditions).
 Step 4 - Signal Wait:  Wait for confirmed pivot marker (▼ or ▲) rather than anticipating based on metrics alone. The marker indicates all detection criteria have aligned.
 Step 5 - Entry Decision:  Use pivot markers as potential reversal zones. Combine with other analysis methods such as support/resistance levels, volume confirmation, and higher timeframe bias for entry decisions.
 Step 6 - Risk Management:  Place stops beyond recent swing structure or ribbon edges. Monitor dashboard STATE—if it flips to CONSTRUCTIVE in trade direction, the reversal may be confirmed; if PIVOT% drops significantly, conditions may be weakening.
 Step 7 - Exit Criteria:  Consider exits when opposite pivot marker appears, STATE changes unfavorably, or standard technical targets are reached.
 Parameter Optimization Guidelines 
 Fast Wave Length:  Adjust to match short-term swing frequency. Shorter values (5-8) for active trading on lower timeframes, longer values (13-20) for swing trading on higher timeframes.
 Slow Wave Length:  Should maintain 2-4x ratio with fast length. Shorter values create more interference cycles, longer values create more stable baseline.
 Phase Detection Length:  Smoothing for phase alignment. Lower values (3-5) for responsive detection, higher values (8-12) for stable readings with less sensitivity.
 Interference Gain:  Amplification multiplier. Lower values (0.5-1.0) for conservative detection, higher values (1.5-2.5) for more sensitive detection.
 Normalization Period:  Rolling window for statistical bounds. Shorter periods (50-100) adapt quickly to volatility changes, longer periods (150-300) provide more stable normalization.
 Interference Threshold:  Minimum amplitude to trigger signals. Lower values (0.50-0.60) generate more signals, higher values (0.70-0.85) are more selective.
 Phase Threshold:  Minimum phase difference in degrees. Lower values (90-110) are more permissive, higher values (140-170) require stronger opposition.
 Min Pivot Spacing:  Bars between signals. Match to average swing duration on your timeframe—tighter spacing (3-8 bars) for scalping, wider spacing (15-30 bars) for swing trading.
 Best Performance Conditions 
This approach works better in markets with:
- Clear swing structure where EMA-based wave analysis is meaningful
- Sufficient volatility for wave separation to develop
- Periodic oscillation between trending and ranging states
- Liquid instruments where EMAs reflect true price flow
This approach may be less effective in:
- Extremely choppy conditions with no directional persistence
- Very low volatility environments where wave separation is minimal  
- Gap-heavy instruments where price discontinuities disrupt wave continuity
- Parabolic moves where waves cannot keep pace with price velocity
The system adapts by reducing signal frequency in poor conditions—when interference stays below threshold or phase alignment remains neutral, pivot markers will not appear.
 Visual Performance Optimization 
The phase field and particle systems are computationally intensive. If experiencing chart lag:
- Reduce Phase Field Layers from 5 to 2-3 (significant performance improvement)
- Lower Particle Density from 3 to 1 (reduces label creation overhead)
- Disable Phase Field entirely (removes most intensive calculations)
- Decrease Matrix History Bars to 15-20 (reduces table computation load)
The core wave analysis and pivot detection continue to function with all visual elements disabled.
 Important Disclaimers 
This indicator is an analytical tool that measures phase relationships and interference amplitude between two exponential moving averages. It identifies conditions where these wave mechanics suggest potential pivot zones based on historical price data analysis. It should not be used as a standalone trading system.
The phase and interference calculations are deterministic mathematical formulas applied to EMA values. These measurements describe current and historical wave relationships but do not predict future price movements. Past wave patterns and pivot markers do not guarantee future market behavior will follow similar patterns.
All trading involves risk. The pivot markers represent analytical conditions where wave mechanics align with specific thresholds, not certainty of directional change. Use appropriate risk management, position sizing, and combine with additional confirmation methods such as support/resistance analysis, volume patterns, and multi-timeframe alignment. No indicator can eliminate false signals or guarantee profitable trades.
The spacing filter and threshold requirements are designed to reduce noise and over-signaling, but market conditions can change rapidly and render any analytical signal invalid. Always use stop losses and never risk capital you cannot afford to lose.
 Technical Implementation Notes 
All calculations execute on closed bars only—there is no repainting of signals or values. The normalization system requires approximately 100 bars of historical data to establish stable statistical bounds; values in the first 50-100 bars may be unstable as the rolling statistics converge. 
Phase field arrays are fixed-size based on the complexity setting. Particle labels are capped at 80 total to prevent excessive memory usage. Dashboard and matrix tables update only on the last bar to minimize computational overhead. Particle generation is throttled to every 2 bars for performance. Phase accumulators use modulo arithmetic (% 2π) to prevent numerical overflow during extended operation.
The indicator has been tested across multiple timeframes (5-minute through daily) and multiple asset classes (forex, stocks, crypto, indices). It functions identically across all instruments due to the adaptive normalization approach.
Quantum Rotational Field MappingQuantum Rotational Field Mapping (QRFM):  
Phase Coherence Detection Through Complex-Plane Oscillator Analysis
 Quantum Rotational Field Mapping  applies complex-plane mathematics and phase-space analysis to oscillator ensembles, identifying high-probability trend ignition points by measuring when multiple independent oscillators achieve phase coherence. Unlike traditional multi-oscillator approaches that simply stack indicators or use boolean AND/OR logic, this system converts each oscillator into a rotating phasor (vector) in the complex plane and calculates the  Coherence Index (CI) —a mathematical measure of how tightly aligned the ensemble has become—then generates signals only when alignment, phase direction, and pairwise entanglement all converge.
The indicator combines three mathematical frameworks:  phasor representation  using analytic signal theory to extract phase and amplitude from each oscillator,  coherence measurement  using vector summation in the complex plane to quantify group alignment, and  entanglement analysis  that calculates pairwise phase agreement across all oscillator combinations. This creates a multi-dimensional confirmation system that distinguishes between random oscillator noise and genuine regime transitions.
 What Makes This Original 
 Complex-Plane Phasor Framework 
This indicator implements classical signal processing mathematics adapted for market oscillators. Each oscillator—whether RSI, MACD, Stochastic, CCI, Williams %R, MFI, ROC, or TSI—is first normalized to a common   scale, then converted into a complex-plane representation using an  in-phase (I)  and  quadrature (Q)  component. The in-phase component is the oscillator value itself, while the quadrature component is calculated as the first difference (derivative proxy), creating a velocity-aware representation.
 From these components, the system extracts: 
 Phase (φ) : Calculated as φ = atan2(Q, I), representing the oscillator's position in its cycle (mapped to -180° to +180°)
 Amplitude (A) : Calculated as A = √(I² + Q²), representing the oscillator's strength or conviction
This mathematical approach is fundamentally different from simply reading oscillator values. A phasor captures both  where  an oscillator is in its cycle (phase angle) and  how strongly  it's expressing that position (amplitude). Two oscillators can have the same value but be in opposite phases of their cycles—traditional analysis would see them as identical, while QRFM sees them as 180° out of phase (contradictory).
 Coherence Index Calculation 
The core innovation is the  Coherence Index (CI) , borrowed from physics and signal processing. When you have N oscillators, each with phase φₙ, you can represent each as a unit vector in the complex plane: e^(iφₙ) = cos(φₙ) + i·sin(φₙ).
 The CI measures what happens when you sum all these vectors: 
 Resultant Vector : R = Σ e^(iφₙ) = Σ cos(φₙ) + i·Σ sin(φₙ)
 Coherence Index : CI = |R| / N
Where |R| is the magnitude of the resultant vector and N is the number of active oscillators.
The CI ranges from 0 to 1:
 CI = 1.0 : Perfect coherence—all oscillators have identical phase angles, vectors point in the same direction, creating maximum constructive interference
 CI = 0.0 : Complete decoherence—oscillators are randomly distributed around the circle, vectors cancel out through destructive interference
 0 < CI < 1 : Partial alignment—some clustering with some scatter
This is not a simple average or correlation. The CI captures  phase synchronization  across the entire ensemble simultaneously. When oscillators phase-lock (align their cycles), the CI spikes regardless of their individual values. This makes it sensitive to regime transitions that traditional indicators miss.
 Dominant Phase and Direction Detection 
Beyond measuring alignment strength, the system calculates the  dominant phase  of the ensemble—the direction the resultant vector points:
 Dominant Phase : φ_dom = atan2(Σ sin(φₙ), Σ cos(φₙ))
This gives the "average direction" of all oscillator phases, mapped to -180° to +180°:
 +90° to -90°  (right half-plane): Bullish phase dominance
 +90° to +180° or -90° to -180°  (left half-plane): Bearish phase dominance
The combination of CI magnitude (coherence strength) and dominant phase angle (directional bias) creates a two-dimensional signal space. High CI alone is insufficient—you need high CI  plus  dominant phase pointing in a tradeable direction. This dual requirement is what separates QRFM from simple oscillator averaging.
 Entanglement Matrix and Pairwise Coherence 
While the CI measures global alignment, the  entanglement matrix  measures local pairwise relationships. For every pair of oscillators (i, j), the system calculates:
 E(i,j) = |cos(φᵢ - φⱼ)| 
This represents the phase agreement between oscillators i and j:
 E = 1.0 : Oscillators are in-phase (0° or 360° apart)
 E = 0.0 : Oscillators are in quadrature (90° apart, orthogonal)
 E between 0 and 1 : Varying degrees of alignment
The system counts how many oscillator pairs exceed a user-defined entanglement threshold (e.g., 0.7). This  entangled pairs count  serves as a confirmation filter: signals require not just high global CI, but also a minimum number of strong pairwise agreements. This prevents false ignitions where CI is high but driven by only two oscillators while the rest remain scattered.
The entanglement matrix creates an N×N symmetric matrix that can be visualized as a web—when many cells are bright (high E values), the ensemble is highly interconnected. When cells are dark, oscillators are moving independently.
 Phase-Lock Tolerance Mechanism 
A complementary confirmation layer is the  phase-lock detector . This calculates the maximum phase spread across all oscillators:
For all pairs (i,j), compute angular distance: Δφ = |φᵢ - φⱼ|, wrapping at 180°
 Max Spread  = maximum Δφ across all pairs
If max spread < user threshold (e.g., 35°), the ensemble is considered  phase-locked —all oscillators are within a narrow angular band.
This differs from entanglement: entanglement measures pairwise cosine similarity (magnitude of alignment), while phase-lock measures maximum angular deviation (tightness of clustering). Both must be satisfied for the highest-conviction signals.
 Multi-Layer Visual Architecture 
QRFM includes six visual components that represent the same underlying mathematics from different perspectives:
 Circular Orbit Plot : A polar coordinate grid showing each oscillator as a vector from origin to perimeter. Angle = phase, radius = amplitude. This is a real-time snapshot of the complex plane. When vectors converge (point in similar directions), coherence is high. When scattered randomly, coherence is low. Users can  see  phase alignment forming before CI numerically confirms it.
 Phase-Time Heat Map : A 2D matrix with rows = oscillators and columns = time bins. Each cell is colored by the oscillator's phase at that time (using a gradient where color hue maps to angle). Horizontal color bands indicate sustained phase alignment over time. Vertical color bands show moments when all oscillators shared the same phase (ignition points). This provides historical pattern recognition.
 Entanglement Web Matrix : An N×N grid showing E(i,j) for all pairs. Cells are colored by entanglement strength—bright yellow/gold for high E, dark gray for low E. This reveals  which  oscillators are driving coherence and which are lagging. For example, if RSI and MACD show high E but Stochastic shows low E with everything, Stochastic is the outlier.
 Quantum Field Cloud : A background color overlay on the price chart. Color (green = bullish, red = bearish) is determined by dominant phase. Opacity is determined by CI—high CI creates dense, opaque cloud; low CI creates faint, nearly invisible cloud. This gives an atmospheric "feel" for regime strength without looking at numbers.
 Phase Spiral : A smoothed plot of dominant phase over recent history, displayed as a curve that wraps around price. When the spiral is tight and rotating steadily, the ensemble is in coherent rotation (trending). When the spiral is loose or erratic, coherence is breaking down.
 Dashboard : A table showing real-time metrics: CI (as percentage), dominant phase (in degrees with directional arrow), field strength (CI × average amplitude), entangled pairs count, phase-lock status (locked/unlocked), quantum state classification ("Ignition", "Coherent", "Collapse", "Chaos"), and collapse risk (recent CI change normalized to 0-100%).
Each component is independently toggleable, allowing users to customize their workspace. The orbit plot is the most essential—it provides intuitive, visual feedback on phase alignment that no numerical dashboard can match.
 Core Components and How They Work Together 
 1. Oscillator Normalization Engine 
The foundation is creating a common measurement scale. QRFM supports eight oscillators:
 RSI : Normalized from   to   using overbought/oversold levels (70, 30) as anchors
 MACD Histogram : Normalized by dividing by rolling standard deviation, then clamped to  
 Stochastic %K : Normalized from   using (80, 20) anchors
 CCI : Divided by 200 (typical extreme level), clamped to  
 Williams %R : Normalized from   using (-20, -80) anchors
 MFI : Normalized from   using (80, 20) anchors
 ROC : Divided by 10, clamped to  
 TSI : Divided by 50, clamped to  
Each oscillator can be individually enabled/disabled. Only active oscillators contribute to phase calculations. The normalization removes scale differences—a reading of +0.8 means "strongly bullish" regardless of whether it came from RSI or TSI.
 2. Analytic Signal Construction 
For each active oscillator at each bar, the system constructs the analytic signal:
 In-Phase (I) : The normalized oscillator value itself
 Quadrature (Q) : The bar-to-bar change in the normalized value (first derivative approximation)
This creates a 2D representation: (I, Q). The phase is extracted as:
φ = atan2(Q, I) × (180 / π)
This maps the oscillator to a point on the unit circle. An oscillator at the same value but rising (positive Q) will have a different phase than one that is falling (negative Q). This velocity-awareness is critical—it distinguishes between "at resistance and stalling" versus "at resistance and breaking through."
The amplitude is extracted as:
A = √(I² + Q²)
This represents the distance from origin in the (I, Q) plane. High amplitude means the oscillator is far from neutral (strong conviction). Low amplitude means it's near zero (weak/transitional state).
3. Coherence Calculation Pipeline
For each bar (or every Nth bar if phase sample rate > 1 for performance):
 Step 1 : Extract phase φₙ for each of the N active oscillators
 Step 2 : Compute complex exponentials: Zₙ = e^(i·φₙ·π/180) = cos(φₙ·π/180) + i·sin(φₙ·π/180)
 Step 3 : Sum the complex exponentials: R = Σ Zₙ = (Σ cos φₙ) + i·(Σ sin φₙ)
 Step 4 : Calculate magnitude: |R| = √ 
 Step 5 : Normalize by count: CI_raw = |R| / N
 Step 6 : Smooth the CI: CI = SMA(CI_raw, smoothing_window)
The smoothing step (default 2 bars) removes single-bar noise spikes while preserving structural coherence changes. Users can adjust this to control reactivity versus stability.
The dominant phase is calculated as:
φ_dom = atan2(Σ sin φₙ, Σ cos φₙ) × (180 / π)
This is the angle of the resultant vector R in the complex plane.
 4. Entanglement Matrix Construction 
For all unique pairs of oscillators (i, j) where i < j:
 Step 1 : Get phases φᵢ and φⱼ
 Step 2 : Compute phase difference: Δφ = φᵢ - φⱼ (in radians)
 Step 3 : Calculate entanglement: E(i,j) = |cos(Δφ)|
 Step 4 : Store in symmetric matrix: matrix  = matrix  = E(i,j)
The matrix is then scanned: count how many E(i,j) values exceed the user-defined threshold (default 0.7). This count is the  entangled pairs  metric.
For visualization, the matrix is rendered as an N×N table where cell brightness maps to E(i,j) intensity.
 5. Phase-Lock Detection 
 Step 1 : For all unique pairs (i, j), compute angular distance: Δφ = |φᵢ - φⱼ|
 Step 2 : Wrap angles: if Δφ > 180°, set Δφ = 360° - Δφ
 Step 3 : Find maximum: max_spread = max(Δφ) across all pairs
 Step 4 : Compare to tolerance: phase_locked = (max_spread < tolerance)
If phase_locked is true, all oscillators are within the specified angular cone (e.g., 35°). This is a boolean confirmation filter.
 6. Signal Generation Logic 
Signals are generated through multi-layer confirmation:
 Long Ignition Signal :
CI crosses above ignition threshold (e.g., 0.80)
 AND  dominant phase is in bullish range (-90° < φ_dom < +90°)
 AND  phase_locked = true
 AND  entangled_pairs >= minimum threshold (e.g., 4)
 Short Ignition Signal :
CI crosses above ignition threshold
 AND  dominant phase is in bearish range (φ_dom < -90° OR φ_dom > +90°)
 AND  phase_locked = true
 AND  entangled_pairs >= minimum threshold
 Collapse Signal :
CI at bar   minus CI at current bar > collapse threshold (e.g., 0.55)
 AND  CI at bar   was above 0.6 (must collapse from coherent state, not from already-low state)
These are strict conditions. A high CI alone does not generate a signal—dominant phase must align with direction, oscillators must be phase-locked, and sufficient pairwise entanglement must exist. This multi-factor gating dramatically reduces false signals compared to single-condition triggers.
 Calculation Methodology 
 Phase 1: Oscillator Computation and Normalization 
On each bar, the system calculates the raw values for all enabled oscillators using standard Pine Script functions:
RSI: ta.rsi(close, length)
MACD: ta.macd() returning histogram component
Stochastic: ta.stoch() smoothed with ta.sma()
CCI: ta.cci(close, length)
Williams %R: ta.wpr(length)
MFI: ta.mfi(hlc3, length)
ROC: ta.roc(close, length)
TSI: ta.tsi(close, short, long)
Each raw value is then passed through a normalization function:
normalize(value, overbought_level, oversold_level) = 2 × (value - oversold) / (overbought - oversold) - 1
This maps the oscillator's typical range to  , where -1 represents extreme bearish, 0 represents neutral, and +1 represents extreme bullish.
For oscillators without fixed ranges (MACD, ROC, TSI), statistical normalization is used: divide by a rolling standard deviation or fixed divisor, then clamp to  .
 Phase 2: Phasor Extraction 
For each normalized oscillator value val:
I = val (in-phase component)
Q = val - val  (quadrature component, first difference)
Phase calculation:
phi_rad = atan2(Q, I)
phi_deg = phi_rad × (180 / π)
Amplitude calculation:
A = √(I² + Q²)
These values are stored in arrays: osc_phases  and osc_amps  for each oscillator n.
 Phase 3: Complex Summation and Coherence 
Initialize accumulators:
sum_cos = 0
sum_sin = 0
For each oscillator n = 0 to N-1:
phi_rad = osc_phases  × (π / 180)
sum_cos += cos(phi_rad)
sum_sin += sin(phi_rad)
Resultant magnitude:
resultant_mag = √(sum_cos² + sum_sin²)
Coherence Index (raw):
CI_raw = resultant_mag / N
Smoothed CI:
CI = SMA(CI_raw, smoothing_window)
Dominant phase:
phi_dom_rad = atan2(sum_sin, sum_cos)
phi_dom_deg = phi_dom_rad × (180 / π)
Phase 4: Entanglement Matrix Population
For i = 0 to N-2:
For j = i+1 to N-1:
phi_i = osc_phases  × (π / 180)
phi_j = osc_phases  × (π / 180)
delta_phi = phi_i - phi_j
E = |cos(delta_phi)|
matrix_index_ij = i × N + j
matrix_index_ji = j × N + i
entangle_matrix  = E
entangle_matrix  = E
if E >= threshold:
  entangled_pairs += 1
The matrix uses flat array storage with index mapping: index(row, col) = row × N + col.
 Phase 5: Phase-Lock Check 
max_spread = 0
For i = 0 to N-2:
For j = i+1 to N-1:
delta = |osc_phases  - osc_phases |
if delta > 180:
delta = 360 - delta
max_spread = max(max_spread, delta)
phase_locked = (max_spread < tolerance)
 Phase 6: Signal Evaluation 
 Ignition Long :
ignition_long = (CI crosses above threshold) AND
(phi_dom > -90 AND phi_dom < 90) AND
phase_locked AND
(entangled_pairs >= minimum)
 Ignition Short :
ignition_short = (CI crosses above threshold) AND
(phi_dom < -90 OR phi_dom > 90) AND
phase_locked AND
(entangled_pairs >= minimum)
 Collapse :
CI_prev = CI 
collapse = (CI_prev - CI > collapse_threshold) AND (CI_prev > 0.6)
All signals are evaluated on bar close. The crossover and crossunder functions ensure signals fire only once when conditions transition from false to true.
 Phase 7: Field Strength and Visualization Metrics 
 Average Amplitude :
avg_amp = (Σ osc_amps ) / N
 Field Strength :
field_strength = CI × avg_amp
 Collapse Risk  (for dashboard):
collapse_risk = (CI  - CI) / max(CI , 0.1)
collapse_risk_pct = clamp(collapse_risk × 100, 0, 100)
 Quantum State Classification :
if (CI > threshold AND phase_locked):
state = "Ignition"
else if (CI > 0.6):
state = "Coherent"
else if (collapse):
state = "Collapse"
else:
state = "Chaos"
 Phase 8: Visual Rendering 
 Orbit Plot : For each oscillator, convert polar (phase, amplitude) to Cartesian (x, y) for grid placement:
radius = amplitude × grid_center × 0.8
x = radius × cos(phase × π/180)
y = radius × sin(phase × π/180)
col = center + x (mapped to grid coordinates)
row = center - y
 Heat Map : For each oscillator row and time column, retrieve historical phase value at lookback = (columns - col) × sample_rate, then map phase to color using a hue gradient.
 Entanglement Web : Render matrix  as table cell with background color opacity = E(i,j).
 Field Cloud : Background color = (phi_dom > -90 AND phi_dom < 90) ? green : red, with opacity = mix(min_opacity, max_opacity, CI).
All visual components render only on the last bar (barstate.islast) to minimize computational overhead.
 How to Use This Indicator 
 Step 1 : Apply QRFM to your chart. It works on all timeframes and asset classes, though 15-minute to 4-hour timeframes provide the best balance of responsiveness and noise reduction.
 Step 2 : Enable the dashboard (default: top right) and the circular orbit plot (default: middle left). These are your primary visual feedback tools.
 Step 3 : Optionally enable the heat map, entanglement web, and field cloud based on your preference. New users may find all visuals overwhelming; start with dashboard + orbit plot.
 Step 4 : Observe for 50-100 bars to let the indicator establish baseline coherence patterns. Markets have different "normal" CI ranges—some instruments naturally run higher or lower coherence.
 Understanding the Circular Orbit Plot 
The orbit plot is a polar grid showing oscillator vectors in real-time:
 Center point : Neutral (zero phase and amplitude)
 Each vector : A line from center to a point on the grid
 Vector angle : The oscillator's phase (0° = right/east, 90° = up/north, 180° = left/west, -90° = down/south)
 Vector length : The oscillator's amplitude (short = weak signal, long = strong signal)
 Vector label : First letter of oscillator name (R = RSI, M = MACD, etc.)
 What to watch :
 Convergence : When all vectors cluster in one quadrant or sector, CI is rising and coherence is forming. This is your pre-signal warning.
 Scatter : When vectors point in random directions (360° spread), CI is low and the market is in a non-trending or transitional regime.
 Rotation : When the cluster rotates smoothly around the circle, the ensemble is in coherent oscillation—typically seen during steady trends.
 Sudden flips : When the cluster rapidly jumps from one side to the opposite (e.g., +90° to -90°), a phase reversal has occurred—often coinciding with trend reversals.
Example: If you see RSI, MACD, and Stochastic all pointing toward 45° (northeast) with long vectors, while CCI, TSI, and ROC point toward 40-50° as well, coherence is high and dominant phase is bullish. Expect an ignition signal if CI crosses threshold.
 Reading Dashboard Metrics 
The dashboard provides numerical confirmation of what the orbit plot shows visually:
 CI : Displays as 0-100%. Above 70% = high coherence (strong regime), 40-70% = moderate, below 40% = low (poor conditions for trend entries).
 Dom Phase : Angle in degrees with directional arrow. ⬆ = bullish bias, ⬇ = bearish bias, ⬌ = neutral.
 Field Strength : CI weighted by amplitude. High values (> 0.6) indicate not just alignment but  strong  alignment.
 Entangled Pairs : Count of oscillator pairs with E > threshold. Higher = more confirmation. If minimum is set to 4, you need at least 4 pairs entangled for signals.
 Phase Lock : 🔒 YES (all oscillators within tolerance) or 🔓 NO (spread too wide).
 State : Real-time classification:
🚀 IGNITION: CI just crossed threshold with phase-lock
⚡ COHERENT: CI is high and stable
💥 COLLAPSE: CI has dropped sharply
🌀 CHAOS: Low CI, scattered phases
 Collapse Risk : 0-100% scale based on recent CI change. Above 50% warns of imminent breakdown.
Interpreting Signals
 Long Ignition (Blue Triangle Below Price) :
Occurs when CI crosses above threshold (e.g., 0.80)
Dominant phase is in bullish range (-90° to +90°)
All oscillators are phase-locked (within tolerance)
Minimum entangled pairs requirement met
 Interpretation : The oscillator ensemble has transitioned from disorder to coherent bullish alignment. This is a high-probability long entry point. The multi-layer confirmation (CI + phase direction + lock + entanglement) ensures this is not a single-oscillator whipsaw.
 Short Ignition (Red Triangle Above Price) :
Same conditions as long, but dominant phase is in bearish range (< -90° or > +90°)
 Interpretation : Coherent bearish alignment has formed. High-probability short entry.
 Collapse (Circles Above and Below Price) :
CI has dropped by more than the collapse threshold (e.g., 0.55) over a 5-bar window
CI was previously above 0.6 (collapsing from coherent state)
 Interpretation : Phase coherence has broken down. If you are in a position, this is an exit warning. If looking to enter, stand aside—regime is transitioning.
 Phase-Time Heat Map Patterns 
Enable the heat map and position it at bottom right. The rows represent individual oscillators, columns represent time bins (most recent on left).
 Pattern: Horizontal Color Bands 
If a row (e.g., RSI) shows consistent color across columns (say, green for several bins), that oscillator has maintained stable phase over time. If  all  rows show horizontal bands of similar color, the entire ensemble has been phase-locked for an extended period—this is a strong trending regime.
 Pattern: Vertical Color Bands 
If a column (single time bin) shows all cells with the same or very similar color, that moment in time had high coherence. These vertical bands often align with ignition signals or major price pivots.
 Pattern: Rainbow Chaos 
If cells are random colors (red, green, yellow mixed with no pattern), coherence is low. The ensemble is scattered. Avoid trading during these periods unless you have external confirmation.
 Pattern: Color Transition 
If you see a row transition from red to green (or vice versa) sharply, that oscillator has phase-flipped. If multiple rows do this simultaneously, a regime change is underway.
 Entanglement Web Analysis 
Enable the web matrix (default: opposite corner from heat map). It shows an N×N grid where N = number of active oscillators.
 Bright Yellow/Gold Cells : High pairwise entanglement. For example, if the RSI-MACD cell is bright gold, those two oscillators are moving in phase. If the RSI-Stochastic cell is bright, they are entangled as well.
 Dark Gray Cells : Low entanglement. Oscillators are decorrelated or in quadrature.
 Diagonal : Always marked with "—" because an oscillator is always perfectly entangled with itself.
 How to use :
Scan for clustering: If most cells are bright, coherence is high across the board. If only a few cells are bright, coherence is driven by a subset (e.g., RSI and MACD are aligned, but nothing else is—weak signal).
Identify laggards: If one row/column is entirely dark, that oscillator is the outlier. You may choose to disable it or monitor for when it joins the group (late confirmation).
Watch for web formation: During low-coherence periods, the matrix is mostly dark. As coherence builds, cells begin lighting up. A sudden "web" of connections forming visually precedes ignition signals.
Trading Workflow
 Step 1: Monitor Coherence Level 
Check the dashboard CI metric or observe the orbit plot. If CI is below 40% and vectors are scattered, conditions are poor for trend entries. Wait.
 Step 2: Detect Coherence Building 
When CI begins rising (say, from 30% to 50-60%) and you notice vectors on the orbit plot starting to cluster, coherence is forming. This is your alert phase—do not enter yet, but prepare.
 Step 3: Confirm Phase Direction 
Check the dominant phase angle and the orbit plot quadrant where clustering is occurring:
Clustering in right half (0° to ±90°): Bullish bias forming
Clustering in left half (±90° to 180°): Bearish bias forming
Verify the dashboard shows the corresponding directional arrow (⬆ or ⬇).
 Step 4: Wait for Signal Confirmation 
Do  not  enter based on rising CI alone. Wait for the full ignition signal:
CI crosses above threshold
Phase-lock indicator shows 🔒 YES
Entangled pairs count >= minimum
Directional triangle appears on chart
This ensures all layers have aligned.
 Step 5: Execute Entry 
 Long : Blue triangle below price appears → enter long
 Short : Red triangle above price appears → enter short
 Step 6: Position Management 
 Initial Stop : Place stop loss based on your risk management rules (e.g., recent swing low/high, ATR-based buffer).
 Monitoring :
Watch the field cloud density. If it remains opaque and colored in your direction, the regime is intact.
Check dashboard collapse risk. If it rises above 50%, prepare for exit.
Monitor the orbit plot. If vectors begin scattering or the cluster flips to the opposite side, coherence is breaking.
 Exit Triggers :
Collapse signal fires (circles appear)
Dominant phase flips to opposite half-plane
CI drops below 40% (coherence lost)
Price hits your profit target or trailing stop
 Step 7: Post-Exit Analysis 
After exiting, observe whether a new ignition forms in the opposite direction (reversal) or if CI remains low (transition to range). Use this to decide whether to re-enter, reverse, or stand aside.
 Best Practices 
 Use Price Structure as Context 
QRFM identifies  when  coherence forms but does not specify  where  price will go. Combine ignition signals with support/resistance levels, trendlines, or chart patterns. For example:
Long ignition near a major support level after a pullback: high-probability bounce
Long ignition in the middle of a range with no structure: lower probability
 Multi-Timeframe Confirmation 
 Open QRFM on two timeframes simultaneously: 
Higher timeframe (e.g., 4-hour): Use CI level to determine regime bias. If 4H CI is above 60% and dominant phase is bullish, the market is in a bullish regime.
Lower timeframe (e.g., 15-minute): Execute entries on ignition signals that align with the higher timeframe bias.
This prevents counter-trend trades and increases win rate.
 Distinguish Between Regime Types 
 High CI, stable dominant phase (State: Coherent) : Trending market. Ignitions are continuation signals; collapses are profit-taking or reversal warnings.
 Low CI, erratic dominant phase (State: Chaos) : Ranging or choppy market. Avoid ignition signals or reduce position size. Wait for coherence to establish.
 Moderate CI with frequent collapses : Whipsaw environment. Use wider stops or stand aside.
 Adjust Parameters to Instrument and Timeframe 
 Crypto/Forex (high volatility) : Lower ignition threshold (0.65-0.75), lower CI smoothing (2-3), shorter oscillator lengths (7-10).
 Stocks/Indices (moderate volatility) : Standard settings (threshold 0.75-0.85, smoothing 5-7, oscillator lengths 14).
 Lower timeframes (5-15 min) : Reduce phase sample rate to 1-2 for responsiveness.
 Higher timeframes (daily+) : Increase CI smoothing and oscillator lengths for noise reduction.
 Use Entanglement Count as Conviction Filter 
 The minimum entangled pairs setting controls signal strictness: 
 Low (1-2) : More signals, lower quality (acceptable if you have other confirmation)
 Medium (3-5) : Balanced (recommended for most traders)
 High (6+) : Very strict, fewer signals, highest quality
Adjust based on your trade frequency preference and risk tolerance.
 Monitor Oscillator Contribution 
Use the entanglement web to see which oscillators are driving coherence. If certain oscillators are consistently dark (low E with all others), they may be adding noise. Consider disabling them. For example:
On low-volume instruments, MFI may be unreliable → disable MFI
On strongly trending instruments, mean-reversion oscillators (Stochastic, RSI) may lag → reduce weight or disable
 Respect the Collapse Signal 
Collapse events are early warnings. Price may continue in the original direction for several bars after collapse fires, but the underlying regime has weakened. Best practice:
If in profit: Take partial or full profit on collapse
If at breakeven/small loss: Exit immediately
If collapse occurs shortly after entry: Likely a false ignition; exit to avoid drawdown
Collapses do not guarantee immediate reversals—they signal  uncertainty .
 Combine with Volume Analysis 
If your instrument has reliable volume:
Ignitions with expanding volume: Higher conviction
Ignitions with declining volume: Weaker, possibly false
Collapses with volume spikes: Strong reversal signal
Collapses with low volume: May just be consolidation
Volume is not built into QRFM (except via MFI), so add it as external confirmation.
 Observe the Phase Spiral 
The spiral provides a quick visual cue for rotation consistency:
 Tight, smooth spiral : Ensemble is rotating coherently (trending)
 Loose, erratic spiral : Phase is jumping around (ranging or transitional)
If the spiral tightens, coherence is building. If it loosens, coherence is dissolving.
 Do Not Overtrade Low-Coherence Periods 
When CI is persistently below 40% and the state is "Chaos," the market is not in a regime where phase analysis is predictive. During these times:
Reduce position size
Widen stops
Wait for coherence to return
QRFM's strength is regime detection. If there is no regime, the tool correctly signals "stand aside."
 Use Alerts Strategically 
 Set alerts for: 
Long Ignition
Short Ignition
Collapse
Phase Lock (optional)
Configure alerts to "Once per bar close" to avoid intrabar repainting and noise. When an alert fires, manually verify:
Orbit plot shows clustering
Dashboard confirms all conditions
Price structure supports the trade
Do not blindly trade alerts—use them as prompts for analysis.
Ideal Market Conditions
Best Performance
 Instruments :
Liquid, actively traded markets (major forex pairs, large-cap stocks, major indices, top-tier crypto)
Instruments with clear cyclical oscillator behavior (avoid extremely illiquid or manipulated markets)
 Timeframes :
15-minute to 4-hour: Optimal balance of noise reduction and responsiveness
1-hour to daily: Slower, higher-conviction signals; good for swing trading
5-minute: Acceptable for scalping if parameters are tightened and you accept more noise
 Market Regimes :
Trending markets with periodic retracements (where oscillators cycle through phases predictably)
Breakout environments (coherence forms before/during breakout; collapse occurs at exhaustion)
Rotational markets with clear swings (oscillators phase-lock at turning points)
 Volatility :
Moderate to high volatility (oscillators have room to move through their ranges)
Stable volatility regimes (sudden VIX spikes or flash crashes may create false collapses)
Challenging Conditions
 Instruments :
Very low liquidity markets (erratic price action creates unstable oscillator phases)
Heavily news-driven instruments (fundamentals may override technical coherence)
Highly correlated instruments (oscillators may all reflect the same underlying factor, reducing independence)
 Market Regimes :
Deep, prolonged consolidation (oscillators remain near neutral, CI is chronically low, few signals fire)
Extreme chop with no directional bias (oscillators whipsaw, coherence never establishes)
Gap-driven markets (large overnight gaps create phase discontinuities)
 Timeframes :
Sub-5-minute charts: Noise dominates; oscillators flip rapidly; coherence is fleeting and unreliable
Weekly/monthly: Oscillators move extremely slowly; signals are rare; better suited for long-term positioning than active trading
 Special Cases :
During major economic releases or earnings: Oscillators may lag price or become decorrelated as fundamentals overwhelm technicals. Reduce position size or stand aside.
In extremely low-volatility environments (e.g., holiday periods): Oscillators compress to neutral, CI may be artificially high due to lack of movement, but signals lack follow-through.
Adaptive Behavior
QRFM is designed to self-adapt to poor conditions:
When coherence is genuinely absent, CI remains low and signals do not fire
When only a subset of oscillators aligns, entangled pairs count stays below threshold and signals are filtered out
When phase-lock cannot be achieved (oscillators too scattered), the lock filter prevents signals
This means the indicator will naturally produce fewer (or zero) signals during unfavorable conditions, rather than generating false signals. This is a  feature —it keeps you out of low-probability trades.
Parameter Optimization by Trading Style
Scalping (5-15 Minute Charts)
 Goal : Maximum responsiveness, accept higher noise
 Oscillator Lengths :
RSI: 7-10
MACD: 8/17/6
Stochastic: 8-10, smooth 2-3
CCI: 14-16
Others: 8-12
 Coherence Settings :
CI Smoothing Window: 2-3 bars (fast reaction)
Phase Sample Rate: 1 (every bar)
Ignition Threshold: 0.65-0.75 (lower for more signals)
Collapse Threshold: 0.40-0.50 (earlier exit warnings)
 Confirmation :
Phase Lock Tolerance: 40-50° (looser, easier to achieve)
Min Entangled Pairs: 2-3 (fewer oscillators required)
 Visuals :
Orbit Plot + Dashboard only (reduce screen clutter for fast decisions)
Disable heavy visuals (heat map, web) for performance
 Alerts :
Enable all ignition and collapse alerts
Set to "Once per bar close"
Day Trading (15-Minute to 1-Hour Charts)
 Goal : Balance between responsiveness and reliability
 Oscillator Lengths :
RSI: 14 (standard)
MACD: 12/26/9 (standard)
Stochastic: 14, smooth 3
CCI: 20
Others: 10-14
 Coherence Settings :
CI Smoothing Window: 3-5 bars (balanced)
Phase Sample Rate: 2-3
Ignition Threshold: 0.75-0.85 (moderate selectivity)
Collapse Threshold: 0.50-0.55 (balanced exit timing)
 Confirmation :
Phase Lock Tolerance: 30-40° (moderate tightness)
Min Entangled Pairs: 4-5 (reasonable confirmation)
 Visuals :
Orbit Plot + Dashboard + Heat Map or Web (choose one)
Field Cloud for regime backdrop
 Alerts :
Ignition and collapse alerts
Optional phase-lock alert for advance warning
Swing Trading (4-Hour to Daily Charts)
 Goal : High-conviction signals, minimal noise, fewer trades
 Oscillator Lengths :
RSI: 14-21
MACD: 12/26/9 or 19/39/9 (longer variant)
Stochastic: 14-21, smooth 3-5
CCI: 20-30
Others: 14-20
 Coherence Settings :
CI Smoothing Window: 5-10 bars (very smooth)
Phase Sample Rate: 3-5
Ignition Threshold: 0.80-0.90 (high bar for entry)
Collapse Threshold: 0.55-0.65 (only significant breakdowns)
 Confirmation :
Phase Lock Tolerance: 20-30° (tight clustering required)
Min Entangled Pairs: 5-7 (strong confirmation)
 Visuals :
All modules enabled (you have time to analyze)
Heat Map for multi-bar pattern recognition
Web for deep confirmation analysis
 Alerts :
Ignition and collapse
Review manually before entering (no rush)
Position/Long-Term Trading (Daily to Weekly Charts)
 Goal : Rare, very high-conviction regime shifts
 Oscillator Lengths :
RSI: 21-30
MACD: 19/39/9 or 26/52/12
Stochastic: 21, smooth 5
CCI: 30-50
Others: 20-30
 Coherence Settings :
CI Smoothing Window: 10-14 bars
Phase Sample Rate: 5 (every 5th bar to reduce computation)
Ignition Threshold: 0.85-0.95 (only extreme alignment)
Collapse Threshold: 0.60-0.70 (major regime breaks only)
 Confirmation :
Phase Lock Tolerance: 15-25° (very tight)
Min Entangled Pairs: 6+ (broad consensus required)
 Visuals :
Dashboard + Orbit Plot for quick checks
Heat Map to study historical coherence patterns
Web to verify deep entanglement
 Alerts :
Ignition only (collapses are less critical on long timeframes)
Manual review with fundamental analysis overlay
Performance Optimization (Low-End Systems)
If you experience lag or slow rendering:
 Reduce Visual Load :
Orbit Grid Size: 8-10 (instead of 12+)
Heat Map Time Bins: 5-8 (instead of 10+)
Disable Web Matrix entirely if not needed
Disable Field Cloud and Phase Spiral
 Reduce Calculation Frequency :
Phase Sample Rate: 5-10 (calculate every 5-10 bars)
Max History Depth: 100-200 (instead of 500+)
 Disable Unused Oscillators :
If you only want RSI, MACD, and Stochastic, disable the other five. Fewer oscillators = smaller matrices, faster loops.
 Simplify Dashboard :
Choose "Small" dashboard size
Reduce number of metrics displayed
These settings will not significantly degrade signal quality (signals are based on bar-close calculations, which remain accurate), but will improve chart responsiveness.
Important Disclaimers
This indicator is a technical analysis tool designed to identify periods of phase coherence across an ensemble of oscillators. It is  not  a standalone trading system and does not guarantee profitable trades. The Coherence Index, dominant phase, and entanglement metrics are mathematical calculations applied to historical price data—they measure past oscillator behavior and do not predict future price movements with certainty.
 No Predictive Guarantee : High coherence indicates that oscillators are currently aligned, which historically has coincided with trending or directional price movement. However, past alignment does not guarantee future trends. Markets can remain coherent while prices consolidate, or lose coherence suddenly due to news, liquidity changes, or other factors not captured by oscillator mathematics.
 Signal Confirmation is Probabilistic : The multi-layer confirmation system (CI threshold + dominant phase + phase-lock + entanglement) is designed to filter out low-probability setups. This increases the proportion of valid signals relative to false signals, but does not eliminate false signals entirely. Users should combine QRFM with additional analysis—support and resistance levels, volume confirmation, multi-timeframe alignment, and fundamental context—before executing trades.
 Collapse Signals are Warnings, Not Reversals : A coherence collapse indicates that the oscillator ensemble has lost alignment. This often precedes trend exhaustion or reversals, but can also occur during healthy pullbacks or consolidations. Price may continue in the original direction after a collapse. Use collapses as risk management cues (tighten stops, take partial profits) rather than automatic reversal entries.
 Market Regime Dependency : QRFM performs best in markets where oscillators exhibit cyclical, mean-reverting behavior and where trends are punctuated by retracements. In markets dominated by fundamental shocks, gap openings, or extreme low-liquidity conditions, oscillator coherence may be less reliable. During such periods, reduce position size or stand aside.
 Risk Management is Essential : All trading involves risk of loss. Use appropriate stop losses, position sizing, and risk-per-trade limits. The indicator does not specify stop loss or take profit levels—these must be determined by the user based on their risk tolerance and account size. Never risk more than you can afford to lose.
 Parameter Sensitivity : The indicator's behavior changes with input parameters. Aggressive settings (low thresholds, loose tolerances) produce more signals with lower average quality. Conservative settings (high thresholds, tight tolerances) produce fewer signals with higher average quality. Users should backtest and forward-test parameter sets on their specific instruments and timeframes before committing real capital.
 No Repainting by Design : All signal conditions are evaluated on bar close using bar-close values. However, the visual components (orbit plot, heat map, dashboard) update in real-time during bar formation for monitoring purposes. For trade execution, rely on the confirmed signals (triangles and circles) that appear only after the bar closes.
 Computational Load : QRFM performs extensive calculations, including nested loops for entanglement matrices and real-time table rendering. On lower-powered devices or when running multiple indicators simultaneously, users may experience lag. Use the performance optimization settings (reduce visual complexity, increase phase sample rate, disable unused oscillators) to improve responsiveness.
This system is most effective when used as  one component  within a broader trading methodology that includes sound risk management, multi-timeframe analysis, market context awareness, and disciplined execution. It is a tool for regime detection and signal confirmation, not a substitute for comprehensive trade planning.
Technical Notes
 Calculation Timing : All signal logic (ignition, collapse) is evaluated using bar-close values. The barstate.isconfirmed or implicit bar-close behavior ensures signals do not repaint. Visual components (tables, plots) render on every tick for real-time feedback but do not affect signal generation.
 Phase Wrapping : Phase angles are calculated in the range -180° to +180° using atan2. Angular distance calculations account for wrapping (e.g., the distance between +170° and -170° is 20°, not 340°). This ensures phase-lock detection works correctly across the ±180° boundary.
 Array Management : The indicator uses fixed-size arrays for oscillator phases, amplitudes, and the entanglement matrix. The maximum number of oscillators is 8. If fewer oscillators are enabled, array sizes shrink accordingly (only active oscillators are processed).
 Matrix Indexing : The entanglement matrix is stored as a flat array with size N×N, where N is the number of active oscillators. Index mapping: index(row, col) = row × N + col. Symmetric pairs (i,j) and (j,i) are stored identically.
 Normalization Stability : Oscillators are normalized to   using fixed reference levels (e.g., RSI overbought/oversold at 70/30). For unbounded oscillators (MACD, ROC, TSI), statistical normalization (division by rolling standard deviation) is used, with clamping to prevent extreme outliers from distorting phase calculations.
 Smoothing and Lag : The CI smoothing window (SMA) introduces lag proportional to the window size. This is intentional—it filters out single-bar noise spikes in coherence. Users requiring faster reaction can reduce the smoothing window to 1-2 bars, at the cost of increased sensitivity to noise.
 Complex Number Representation : Pine Script does not have native complex number types. Complex arithmetic is implemented using separate real and imaginary accumulators (sum_cos, sum_sin) and manual calculation of magnitude (sqrt(real² + imag²)) and argument (atan2(imag, real)).
 Lookback Limits : The indicator respects Pine Script's maximum lookback constraints. Historical phase and amplitude values are accessed using the   operator, with lookback limited to the chart's available bar history (max_bars_back=5000 declared).
 Visual Rendering Performance : Tables (orbit plot, heat map, web, dashboard) are conditionally deleted and recreated on each update using table.delete() and table.new(). This prevents memory leaks but incurs redraw overhead. Rendering is restricted to barstate.islast (last bar) to minimize computational load—historical bars do not render visuals.
 Alert Condition Triggers : alertcondition() functions evaluate on bar close when their boolean conditions transition from false to true. Alerts do not fire repeatedly while a condition remains true (e.g., CI stays above threshold for 10 bars fires only once on the initial cross).
 Color Gradient Functions : The phaseColor() function maps phase angles to RGB hues using sine waves offset by 120° (red, green, blue channels). This creates a continuous spectrum where -180° to +180° spans the full color wheel. The amplitudeColor() function maps amplitude to grayscale intensity. The coherenceColor() function uses cos(phase) to map contribution to CI (positive = green, negative = red).
 No External Data Requests : QRFM operates entirely on the chart's symbol and timeframe. It does not use request.security() or access external data sources. All calculations are self-contained, avoiding lookahead bias from higher-timeframe requests.
 Deterministic Behavior : Given identical input parameters and price data, QRFM produces identical outputs. There are no random elements, probabilistic sampling, or time-of-day dependencies.
— Dskyz, Engineering precision. Trading coherence.
RSI & VWAP StrategyRSI & VWAP 'Buy the Dip' Strategy with Advanced Trailing Stop
Strategy Overview
This is a long-only, mean-reversion "buy the dip" strategy designed to identify and capitalize on oversold conditions in the market. The core philosophy is to enter positions when an asset is technically oversold (confirmed by RSI) and trading at a "discount" relative to its recent volume (confirmed by VWAP).
The strategy does not just look for weakness; it waits for a single bar of bullish confirmation (a green candle) before triggering an entry. This helps to filter out "falling knives" and improves the quality of the entry signal.
The true power of this script lies in its sophisticated position management, which includes:
Smart Pyramiding: A "scale-in" feature that allows you to add to your position at cheaper prices.
Dual-Mode Exit System: You can choose between a simple, fixed Stop-Loss/Take-Profit or an advanced, multi-stage trailing stop designed to protect profits and let winners run.
1. The Entry Signal: "The Dip"
A buy signal (marked by a green triangle below the bar) is generated only when all three of the following conditions are met simultaneously:
RSI is Oversold: The RSI value drops below the user-defined RSI Oversold Level (default: 30). This identifies technically oversold weakness.
Price is Below VWAP: The closing price is below the Volume-Weighted Average Price. This indicates the price is "cheap" relative to where the majority of volume has traded.
Bullish Confirmation Bar: The bar itself must be green (close > open). This acts as a confirmation signal, showing that buyers are stepping in to defend the oversold/undervalued level.
2. Position Management: Smart Pyramiding
This strategy allows for pyramiding (default: 1 additional entry). However, it doesn't just buy every new signal. It uses a "Smart Pyramiding" feature controlled by the "Percent Decrease" input.
How it works: When a new buy signal appears after you are already in a position, the strategy checks the Percent Decrease value.
Example (Percent Decrease = 5%): The strategy will only add to your position if the new entry price is at least 5% lower than your last entry price. This is an "average down" or "scale-in" feature that ensures you only add to your position at significantly better prices.
If set to 0%: The strategy will add to the position on any new valid buy signal (up to the pyramid limit).
3. The Dual-Mode Exit System
This is the most advanced feature of the script. You can choose your exit logic using the "Enable Trailing Stop" checkbox.
Mode 1: Standard SL/TP (Trailing Stop = OFF)
This is the simple, traditional exit mode.
It uses a fixed percentage-based Stop Loss and Take Profit.
These are calculated from the strategy.position_avg_price (your average entry cost).
Ideal for straightforward backtesting or a "set it and forget it" approach.
Mode 2: Advanced Trailing Stop (Trailing Stop = ON)
This is a dynamic, multi-phase exit logic designed to maximize gains and protect profits. It works in three distinct phases:
Phase 1: Entry (No Stop-Loss)
CRITICAL: When a position is first opened in this mode, no stop-loss is active. This is a deliberate design choice to avoid being stopped out by initial volatility before the trade has a chance to move in your favor. The position is "naked" until it hits the first profit target.
Phase 2: Activation (Breakeven Trigger)
When the price's high reaches your "First Profit Target (%)" (default: 5%), the trailing stop activates.
The script now begins tracking the highestPrice achieved since activation.
Phase 3: Trailing & Profit Protection
Once activated, the script places a dynamic stop-loss at a distance of "Trailing Pullback Stop (%)" (default: 3%) below the highestPrice.
Profit Lock-In: This stop-loss can only move up. It includes a breakeven-plus feature (math.max(trailingStopLevel, entryPrice)). This means that once your stop is activated, it will never move back below your average entry price, effectively guaranteeing that a winning trade cannot turn into a loss.
Example: Your First Profit Target is 5% and Trailing Pullback is 3%. The trade goes to +5% (trail activates, breakeven stop is placed). It then goes to +10% (stop moves up to +7%). If the price then falls to +6.9%, you are stopped out with a +7% gain.
Pyramid-Reset Logic: If you pyramid into a position (add a second entry), the entire Trailing Stop mechanism resets. The strategy.position_avg_price is recalculated, and the logic returns to Phase 1 (No Stop-Loss) until the new First Profit Target is hit based on the new average cost.
Key Inputs & Features
RSI Settings: RSI Period and RSI Oversold Level to fine-tune the entry signal.
ADVANCE SETTINGS:
Use Percentage Decrease?: Enables the "Smart Pyramiding" feature.
Percent Decrease: The percentage discount required for a pyramid entry.
TRAILING STOP (Group):
Enable Trailing Stop: The master switch for the exit logic (Mode 1 vs. Mode 2).
First Profit Target (%): The percentage gain required to activate the trailing stop.
Trailing Pullback Stop (%): How "tight" the trailing stop will be once active.
Standard SL/TP (Group):
Stop Loss %: Used only if the Trailing Stop is OFF.
Take Profit %: Used only if the Trailing Stop is OFF.
Backtesting Date Range: Built-in date filters allow you to easily test the strategy's performance during specific market periods (e.g., bull markets, bear markets, or choppy ranges).
How to Use & Recommendations
Test Both Exit Modes: Run backtests using both the Standard SL/TP mode and the Advanced Trailing Stop mode to see which performs better on your asset and timeframe.
Understand the Risk: Be fully aware that in Advanced Trailing Mode, there is no hard stop-loss between your entry and the "First Profit Target." This requires a higher risk tolerance but can prevent premature stop-outs.
Tune for Your Asset: This is a mean-reversion strategy. It may perform best in markets that are ranging or "choppy." It may perform poorly in very strong, one-directional trending markets. Adjust the RSI and Percent Decrease settings to match the volatility of your chosen asset.
Disclaimer: This script is for educational and informational purposes only. It is not financial advice. All trading involves risk, and past performance is not indicative of future results. Please conduct your own thorough backtesting and research before using this strategy with real funds.
RSI Divergence + Structure Break Alert (M3) Pr.T.TProfessional Trader Trường, chỉ báo này tôi rất tâm đắc là chỉ báo đầu tiên của tôi
3 Lines RCI + Psy + ADX Title: 3 Lines RCI + Psy + ADX (Integrated)
Description:
An all-in-one indicator combining RCI (short, mid, long), Psychological Line (Psy), and ADX.
RCI: Shows overbought/oversold zones and trend potential.
Psy: Measures market sentiment with adjustable thresholds.
ADX: Indicates trend strength with color-coded levels.
Use it to identify reversals, confirm trend strength, and improve entry/exit timing. Fully customizable for different trading styles.






















