Swing High/Low Scalper(Mastersinnifty)Overview 
The Swing High/Low Scalper is designed for traders seeking structured entries and disciplined stop-loss planning during momentum shifts. It combines smoothed Force Index readings with swing high/low analysis to identify moments where both momentum and structural price levels align.
When a new directional bias is confirmed, the indicator plots clear entry signals and dynamically calculates the nearest logical stop-loss level based on recent swing points.
---
 Core Logic 
- Force Index Bias Detection
    - The Force Index (price × volume change) is smoothed with an EMA to determine sustained bullish or bearish momentum.
- Signal Memory and Noise Reduction
    - The indicator remembers the last signal (buy/sell) and only triggers a new signal when the bias changes, helping avoid redundant entries in sideways or noisy conditions.
- Swing-based Stop-Loss Calculation
    - Upon signal confirmation, the script automatically plots a stop-loss label near the most recent swing low (for buys) or swing high (for sells).
    - If conditions are extreme, fallback safety checks are used to validate the stop-loss placement.
---
 Key Features 
- Dynamic, structure-based stop-loss plots at every trade signal.
- Visual background bias:
    - Green tint = Bullish bias
    - Red tint = Bearish bias
- Minimalist and clean chart visualization for easy interpretation.
- Designed for scalability across timeframes (from 1-minutes to daily charts).
---
 Why It’s Unique 
- Unlike simple momentum oscillators or swing indicators, this tool integrates a state-tracking mechanism.
- A signal is only generated when a true shift in directional force occurs and swing structure supports the move, seeking to catch only meaningful changes rather than every minor fluctuation.
- This dual-filter approach emphasizes quality over quantity, aiming for disciplined entries with risk levels derived from actual price behavior, not arbitrary formulas.
---
 How to Use 
- Apply the Script to your desired chart and timeframe.
- Look for Signals:
    - Green Up Arrow = Buy Signal
    - Red Down Arrow = Sell Signal
- Observe Stop-Loss Labels
    - Use the plotted SL labels for setting exit points based on recent swing structure.
- Monitor Background Bias:
    - Green or Red background hints at prevailing directional momentum.
---
 Important Disclaimer 
This tool is intended to assist technical analysis and trade planning.
It does not provide financial advice or guarantee any future performance.
Always use additional risk management practices when trading.
"scalping"に関するスクリプトを検索
EMA SCALPEUR SHORTI'm trying to find the best EMA's for scalpingm you are able to choose 2 differents EMAs for your enter and 2 differents EMAs for you exit.
It's putting entry and exit on the graph
Supply and Demand Zone IndicatorOVERVIEW 
The supply and demand zone indicator shows real-time supply and demand zones on the chart. It also plots a table including the high and low values of the zones. The last row of the table also shows the daily trend in the market.
 CONCEPTS 
 What is Supply & Demand? 
Supply and Demand represent the two most powerful forces of the forex market. Demand means the number of buyers buying a security in the market. Supply means the number of sellers selling a security in the market.
 How to identify supply and demand zones? 
Supply and Demand zones are formed on the base region of price on the chart. There are two types of movement of price in technical analysis.
 
 Impulsive wave
 Retracement wave
 
  
The impulsive wave represents the price movement of market makers. The Retracement wave indicates base regions where market makers decide their next direction to go up or down.
There are four fundamental concepts of Demand and supply in forex.
 
 Rally Base Rally (RBR)
 Rally Base Drop (RBD)
 Drop Base Rally (DBR)
 Drop Base Drop (DBD)
 
 How does supply & demand indicator work? 
Our supply & demand indicator will use a simple formula based on price action to plot the zones. It will plot the zone on the base candles using the high and low of the base zone. 
 Base candle = a candlestick that has a small body and big shadows like a Doji candlestick. 
 Big candle = a candlestick with a large body and small shadows. 
The zone will be drawn on the high and low of the base candlestick. There can be more than one base candlesticks in the base zone, but our indicator will identify the maximum of 4 base candlesticks.
 FEATURES 
 
  Specify desired Big Body Candle Size Percentage
  Specify desired Small Body Candle Size Percentage
  Change the Colors of Zones at your own will
  The Indicator Draws the latest zones and puts a label on historical Zones
  The Indicator  Draws real-time Zones under specified conditions of candle body sizes. The Zone will stop once the candlestick closes above the supply zone or below demand zones.
 Recommended Timeframe 
Above 30 Minutes
Volatility Detector by AjeetThis indicator is used for detecting Volatility
To be applied only on 15 mins chart
As soon as you spot a circle (Inc. in Volatility) then high movement is 
expected in further 5-6 candles
Movement can be up or down 
Its can be best used for scalping...
Run a chart on 15 mins, detect a candle with an indication of high movement ahead
shift to smaller timeframe like 3 mins
apply lower setting supertrend like 11,2
and take benefit of the move
Capns Bollinger Bands MTF This Simple Script display higher time frame Bollinger Band  on current resolution . Etc : On 1 Minutes chart BB Band is 5 Minutes Band. I use this code on my pc for scalping...Hope You like the idea
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
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.
[Yorsh] BJN CTF FVG & Trade Helper v1.01. Executive Summary
The   BJN CTF FVG & Trade Helper v1.0 is an advanced, systematic trading tool designed for precision and objectivity in the futures market. Built on the high-speed PineScript v6, this indicator moves beyond simple FVG plotting by integrating a complete, rules-based trade execution model known as the "iFVG" (inverted Fair Value Gap) setup.
Its core purpose is to identify specific, high-probability trade scenarios, validate their structural integrity, and provide an automated position sizing and risk management visual directly on the chart. The indicator's primary competitive advantage lies in its strict, logical trade validation engine and its unwavering focus on performance, ensuring it can analyze complex market structures in real-time without causing chart lag. It is a complete "trade helper" designed to enforce discipline and automate complex analysis.
2. Core Features Overview
This indicator is built around a proprietary trade logic engine that automates a sophisticated trading model from start to finish (www.bjnfx.com).
A. Intelligent Fair Value Gap (FVG) Detection
Dynamic Sizing Rules: The indicator doesn't just find FVGs; it qualifies them. It automatically applies different minimum size requirements (in points) for the volatile NY session versus quieter, non-NY hours, filtering out insignificant noise.
Composite FVG Merging: In a unique and advanced feature, the script can identify two small, back-to-back, invalid FVGs and merge them into a single, valid composite FVG. This allows it to find powerful trade setups that other FVG indicators would miss entirely.
Live FVG Hints: An optional feature shows potential FVGs forming on the live, developing candle, giving you a valuable edge in anticipating the next setup.
B. The "iFVG" Trade Logic Engine
This is the heart of the indicator. It's a complete, long/short trading model that operates in distinct states:
Detection: Identifies a valid FVG.
Inversion: Waits for price to decisively close through the FVG, turning it from a potential continuation area into an "inversion" point (iFVG).
Structural Validation: This is the critical step. Before confirming a trade, the engine performs a rigorous, automated scan of the entire price leg to ensure:
The Invalidation Point (IP)—the last protective swing high/low—has not been contaminated.
No opposing "Hazard" FVGs have been touched, which would compromise the setup.
Confirmation: If the structure is clean, the indicator signals a confirmed trade setup with a marker ('L' for Long, 'S' for Short) and highlights the trigger candle.
C. Automated Position Sizing & Risk Management
Upon a confirmed trade signal, the "Trade Helper" instantly activates:
Dynamic Stop Loss Calculation: The SL is not placed arbitrarily. It is intelligently calculated based on the most logical structural point within the trading leg, using other nearby FVGs as potential support/resistance.
Bracketed Sizing: Based on the calculated SL in points, the indicator references a built-in risk matrix to determine the appropriate number of contracts to trade (e.g., a 5-point SL might suggest 10 contracts, while a 10-point SL suggests 5). This enforces consistent risk.
Full Visual Overlay: It draws a clear, color-coded box on your chart showing the precise Entry, Stop Loss (SL), Hard Stop (2x SL), and Take Profit (TP) levels, along with the calculated contract size.
D. Informative Status Panel
A clean, non-intrusive panel at the bottom of the screen keeps you constantly aware of the trade engine's status. It clearly displays whether the Bullish and Bearish engines are "Idle," "Armed" (a setup is developing), "Triggered," or "Invalidated," so you always know what the script is monitoring.
3. The Performance Advantage: Built for Speed and Scalpers
High-frequency logic can cripple a trading platform. This indicator was built from the ground up to prevent that, making it superior for traders who value a responsive, lag-free experience.
Strict Bar Lookback (maxLookbackBars): This is the key performance feature. The user defines a maximum number of historical bars (e.g., 200) for the script to analyze. Any FVG or price structure older than this limit is completely ignored and removed from memory. This prevents the script from bogging down your chart with thousands of irrelevant historical objects.
Timeframe-Specific History Limits: The script automatically applies even stricter history limits on lower timeframes (e.g., 15-second charts only process the last 15 minutes of data), ensuring it remains exceptionally fast for scalping.
Surgical Array Pruning: On every bar, the indicator actively scans its memory for "stale" FVG objects that have fallen outside the lookback window. It then deletes their drawings and removes them from the active array, ensuring the logic engine is only ever processing a small, relevant, and recent dataset.
Efficient State Management: The logic is contained within a highly structured "engine." This prevents redundant calculations and ensures complex structural scans are only performed when a potential trade is actively developing, not on every single price tick.
The result is an institutional-grade algorithmic tool that runs with the speed and lightness of a simple moving average, giving you a decisive edge in execution.
4. Ideal User Profile
This indicator is purpose-built for:
Systematic & Rules-Based Traders: Individuals who want to remove emotion and subjectivity and trade a precise, repeatable model.
Scalpers & Intraday Futures Traders: Particularly those on NQ/MNQ, who require a high-performance tool that can keep up with fast-moving markets.
ICT iFVG Traders: Traders familiar with FVGs/iFVGs, invalidation points, and structural validation will find this tool automates the most tedious and error-prone parts of their analysis.
5. Conclusion
The   BJN CTF FVG & Trade Helper v1.0 is more than just an indicator; it is a semi-automated trading assistant. It provides a clear, objective, and highly-validated trade model designed to enforce discipline. Its defining characteristic is its sophisticated logic engine, combined with a performance-first architecture that sets a new standard for what traders should expect from their analytical tools. For the systematic trader, it offers an unparalleled blend of precision, automation, and speed.
10scalpingThis is a private invite-only signal indicator designed for 10-second chart scalping.
It helps identify short-term entry and exit points based on a proprietary internal logic.
The source code is fully hidden and access is limited to approved users only.
Redistribution or public sharing of this script is not permitted.
このインジケーターは、10秒足スキャルピング向けに設計された招待制のシグナルツールです。
独自の内部ロジックに基づき、短期的なエントリー・イグジットポイントを示します。
ソースコードは完全に非公開で、許可されたユーザーのみが利用できます。
再配布や公開共有は禁止されています。
Kalman VWAP Filter [BackQuant]Kalman VWAP Filter  
 A precision-engineered price estimator that fuses  Kalman filtering  with the  Volume-Weighted Average Price (VWAP)  to create a smooth, adaptive representation of fair value. This hybrid model intelligently balances responsiveness and stability, tracking trend shifts with minimal noise while maintaining a statistically grounded link to volume distribution.
 If you would like to see my original Kalman Filter, please find it here: 
 
 Concept overview 
 The Kalman VWAP Filter is built on two core ideas from quantitative finance and control theory:
  
  Kalman filtering  — a recursive Bayesian estimator used to infer the true underlying state of a noisy system (in this case, fair price).
  VWAP anchoring  — a dynamic reference that weights price by traded volume, representing where the majority of transactions have occurred.
  
 By merging these concepts, the filter produces a line that behaves like a "smart moving average": smooth when noise is high, fast when markets trend, and self-adjusting based on both market structure and user-defined noise parameters.
 How it works 
  
  Measurement blend : Combines the chosen  Price Source  (e.g., close or hlc3) with either a  Session VWAP  or a  Rolling VWAP  baseline. The  VWAP Weight  input controls how much the filter trusts traded volume versus price movement.
  Kalman recursion : Each bar updates an internal "state estimate" using the Kalman gain, which determines how much to trust new observations vs. the prior state.
  Noise parameters :
 Process Noise  controls agility — higher values make the filter more responsive but also more volatile.
 Measurement Noise  controls smoothness — higher values make it steadier but slower to adapt.
  Filter order (N) : Defines how many parallel state estimates are used. Larger orders yield smoother output by layering multiple one-dimensional Kalman passes.
  Final output : A refined price trajectory that captures VWAP-adjusted fair value while dynamically adjusting to real-time volatility and order flow.
  
 Why this matters 
 Most smoothing techniques (EMA, SMA, Hull) trade off lag for smoothness. Kalman filtering, however, adaptively rebalances that tradeoff each bar using probabilistic weighting, allowing it to follow market state changes more efficiently. Anchoring it to VWAP integrates microstructure context — capturing where liquidity truly lies rather than only where price moves.
 Use cases 
  
  Trend tracking : Color-coded candle painting highlights shifts in slope direction, revealing early trend transitions.
  Fair value mapping : The line represents a continuously updated equilibrium price between raw price action and VWAP flow.
  Adaptive moving average replacement : Outperforms static MAs in variable volatility regimes by self-adjusting smoothness.
  Execution & reversion logic : When price diverges from the Kalman VWAP, it may indicate short-term imbalance or overextension relative to volume-adjusted fair value.
  Cross-signal framework : Use with standard VWAP or other filters to identify convergence or divergence between liquidity-weighted and state-estimated prices.
  
 Parameter guidance 
  
  Process Noise : 0.01–0.05 for swing traders, 0.1–0.2 for intraday scalping.
  Measurement Noise : 2–5 for normal use, 8+ for very smooth tracking.
  VWAP Weight : 0.2–0.4 balances both price and VWAP influence; 1.0 locks output directly to VWAP dynamics.
  Filter Order (N) : 3–5 for reactive short-term filters; 8–10 for smoother institutional-style baselines.
  
 Interpretation 
  
  When  price > Kalman VWAP  and slope is positive → bullish pressure; buyers dominate above fair value.
  When  price < Kalman VWAP  and slope is negative → bearish pressure; sellers dominate below fair value.
  Convergence of price and Kalman VWAP often signals equilibrium; strong divergence suggests imbalance.
  Crosses between Kalman VWAP and the base VWAP can hint at shifts in short-term vs. long-term liquidity control.
  
 Summary 
 The  Kalman VWAP Filter  blends statistical estimation with market microstructure awareness, offering a refined alternative to static smoothing indicators. It adapts in real time to volatility and order flow, helping traders visualize balance, transition, and momentum through a lens of probabilistic fair value rather than simple price averaging.
Ehlers Autocorrelation Periodogram (EACP)# EACP: Ehlers Autocorrelation Periodogram
## Overview and Purpose
Developed by John F. Ehlers (Technical Analysis of Stocks & Commodities, Sep 2016), the Ehlers Autocorrelation Periodogram (EACP) estimates the dominant market cycle by projecting normalized autocorrelation coefficients onto Fourier basis functions. The indicator blends a roofing filter (high-pass + Super Smoother) with a compact periodogram, yielding low-latency dominant cycle detection suitable for adaptive trading systems. Compared with Hilbert-based methods, the autocorrelation approach resists aliasing and maintains stability in noisy price data.
EACP answers a central question in cycle analysis: “What period currently dominates the market?” It prioritizes spectral power concentration, enabling downstream tools (adaptive moving averages, oscillators) to adjust responsively without the lag present in sliding-window techniques.
## Core Concepts
* **Roofing Filter:** High-pass plus Super Smoother combination removes low-frequency drift while limiting aliasing.
* **Pearson Autocorrelation:** Computes normalized lag correlation to remove amplitude bias.
* **Fourier Projection:** Sums cosine and sine terms of autocorrelation to approximate spectral energy.
* **Gain Normalization:** Automatic gain control prevents stale peaks from dominating power estimates.
* **Warmup Compensation:** Exponential correction guarantees valid output from the very first bar.
## Implementation Notes
**This is not a strict implementation of the TASC September 2016 specification.** It is a more advanced evolution combining the core 2016 concept with techniques Ehlers introduced later. The fundamental Wiener-Khinchin theorem (power spectral density = Fourier transform of autocorrelation) is correctly implemented, but key implementation details differ:
### Differences from Original 2016 TASC Article
1. **Dominant Cycle Calculation:**
   - **2016 TASC:** Uses peak-finding to identify the period with maximum power
   - **This Implementation:** Uses Center of Gravity (COG) weighted average over bins where power ≥ 0.5
   - **Rationale:** COG provides smoother transitions and reduces susceptibility to noise spikes
2. **Roofing Filter:**
   - **2016 TASC:** Simple first-order high-pass filter
   - **This Implementation:** Canonical 2-pole high-pass with √2 factor followed by Super Smoother bandpass
   - **Formula:** `hp := (1-α/2)²·(p-2p +p ) + 2(1-α)·hp  - (1-α)²·hp `
   - **Rationale:** Evolved filtering provides better attenuation and phase characteristics
3. **Normalized Power Reporting:**
   - **2016 TASC:** Reports peak power across all periods
   - **This Implementation:** Reports power specifically at the dominant period
   - **Rationale:** Provides more meaningful correlation between dominant cycle strength and normalized power
4. **Automatic Gain Control (AGC):**
   - Uses decay factor `K = 10^(-0.15/diff)` where `diff = maxPeriod - minPeriod`
   - Ensures K < 1 for proper exponential decay of historical peaks
   - Prevents stale peaks from dominating current power estimates
### Performance Characteristics
- **Complexity:** O(N²) where N = (maxPeriod - minPeriod)
- **Implementation:** Uses `var` arrays with native PineScript historical operator ` `
- **Warmup:** Exponential compensation (§2 pattern) ensures valid output from bar 1
### Related Implementations
This refined approach aligns with:
- TradingView TASC 2025.02 implementation by blackcat1402
- Modern Ehlers cycle analysis techniques post-2016
- Evolved filtering methods from *Cycle Analytics for Traders*
The code is mathematically sound and production-ready, representing a refined version of the autocorrelation periodogram concept rather than a literal translation of the 2016 article.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Min Period | 8 | Lower bound of candidate cycles | Increase to ignore microstructure noise; decrease for scalping. |
| Max Period | 48 | Upper bound of candidate cycles | Increase for swing analysis; decrease for intraday focus. |
| Autocorrelation Length | 3 | Averaging window for Pearson correlation | Set to 0 to match lag, or enlarge for smoother spectra. |
| Enhance Resolution | true | Cubic emphasis to highlight peaks | Disable when a flatter spectrum is desired for diagnostics. |
**Pro Tip:** Keep `(maxPeriod - minPeriod)` ≤ 64 to control $O(n^2)$ inner loops and maintain responsiveness on lower timeframes.
## Calculation and Mathematical Foundation
**Explanation:**
1. Apply roofing filter to `source` using coefficients $\alpha_1$, $a_1$, $b_1$, $c_1$, $c_2$, $c_3$.
2. For each lag $L$ compute Pearson correlation $r_L$ over window $M$ (default $L$).
3. For each period $p$, project onto Fourier basis:
   $C_p=\sum_{n=2}^{N} r_n \cos\left(\frac{2\pi n}{p}\right)$ and $S_p=\sum_{n=2}^{N} r_n \sin\left(\frac{2\pi n}{p}\right)$.
4. Power $P_p=C_p^2+S_p^2$, smoothed then normalized via adaptive peak tracking.
5. Dominant cycle $D=\frac{\sum p\,\tilde P_p}{\sum \tilde P_p}$ over bins where $\tilde P_p≥0.5$, warmup-compensated.
**Technical formula:**
```
Step 1: hp_t = ((1-α₁)/2)(src_t - src_{t-1}) + α₁ hp_{t-1}
Step 2: filt_t = c₁(hp_t + hp_{t-1})/2 + c₂ filt_{t-1} + c₃ filt_{t-2}
Step 3: r_L = (M Σxy - Σx Σy) / √ 
Step 4: P_p = (Σ_{n=2}^{N} r_n cos(2πn/p))² + (Σ_{n=2}^{N} r_n sin(2πn/p))²
Step 5: D = Σ_{p∈Ω} p · ĤP_p / Σ_{p∈Ω} ĤP_p with warmup compensation
```
> 🔍 **Technical Note:** Warmup uses $c = 1 / (1 - (1 - \alpha)^{k})$ to scale early-cycle estimates, preventing low values during initial bars.
## Interpretation Details
- **Primary Dominant Cycle:**
  - High $D$ (e.g., > 30) implies slow regime; adaptive MAs should lengthen.
  - Low $D$ (e.g., < 15) signals rapid oscillations; shorten lookback windows.
- **Normalized Power:**
  - Values > 0.8 indicate strong cycle confidence; consider cyclical strategies.
  - Values < 0.3 warn of flat spectra; favor trend or volatility approaches.
- **Regime Shifts:**
  - Rapid drop in $D$ alongside rising power often precedes volatility expansion.
  - Divergence between $D$ and price swings may highlight upcoming breakouts.
## Limitations and Considerations
- **Spectral Leakage:** Limited lag range can smear peaks during abrupt volatility shifts.
- **O(n²) Segment:** Although constrained (≤ 60 loops), wide period spans increase computation.
- **Stationarity Assumption:** Autocorrelation presumes quasi-stationary cycles; regime changes reduce accuracy.
- **Latency in Noise:** Even with roofing, extremely noisy assets may require higher `avgLength`.
- **Downtrend Bias:** Negative trends may clip high-pass output; ensure preprocessing retains signal.
## References
* Ehlers, J. F. (2016). “Past Market Cycles.” *Technical Analysis of Stocks & Commodities*, 34(9), 52-55.
* Thinkorswim Learning Center. “Ehlers Autocorrelation Periodogram.”
* Fab MacCallini. “autocorrPeriodogram.R.” GitHub repository.
* QuantStrat TradeR Blog. “Autocorrelation Periodogram for Adaptive Lookbacks.”
* TradingView Script by blackcat1402. “Ehlers Autocorrelation Periodogram (Updated).”
COT IndexTHE HIDDEN INTELLIGENCE IN FUTURES MARKETS
What if you could see what the smartest players in the futures markets are doing before the crowd catches on? While retail traders chase momentum indicators and moving averages, obsess over Japanese candlestick patterns, and debate whether the RSI should be set to fourteen or twenty-one periods, institutional players leave footprints in the sand through their mandatory reporting to the Commodity Futures Trading Commission. These footprints, published weekly in the Commitment of Traders reports, have been hiding in plain sight for decades, available to anyone with an internet connection, yet remarkably few traders understand how to interpret them correctly. The COT Index indicator transforms this raw institutional positioning data into actionable trading signals, bringing Wall Street intelligence to your trading screen without requiring expensive Bloomberg terminals or insider connections.
The uncomfortable truth is this: Most retail traders operate in a binary world. Long or short. Buy or sell. They apply technical analysis to individual positions, constrained by limited capital that forces them to concentrate risk in single directional bets. Meanwhile, institutional traders operate in an entirely different dimension. They manage portfolios dynamically weighted across multiple markets, adjusting exposure based on evolving market conditions, correlation shifts, and risk assessments that retail traders never see. A hedge fund might be simultaneously long gold, short oil, neutral on copper, and overweight agricultural commodities, with position sizes calibrated to volatility and portfolio Greeks. When they increase gold exposure from five percent to eight percent of portfolio allocation, this rebalancing decision reflects sophisticated analysis of opportunity cost, risk parity, and cross-market dynamics that no individual chart pattern can capture.
This portfolio reweighting activity, multiplied across hundreds of institutional participants, manifests in the aggregate positioning data published weekly by the CFTC. The Commitment of Traders report does not show individual trades or strategies. It shows the collective footprint of how actual commercial hedgers and large speculators have allocated their capital across different markets. When mining companies collectively increase forward gold sales to hedge thirty percent more production than last quarter, they are not reacting to a moving average crossover. They are making strategic allocation decisions based on production forecasts, cost structures, and price expectations derived from operational realities invisible to outside observers. This is portfolio management in action, revealed through positioning data rather than price charts.
If you want to understand how institutional capital actually flows, how sophisticated traders genuinely position themselves across market cycles, the COT report provides a rare window into that hidden world. But understand what you are getting into. This is not a tool for scalpers seeking confirmation of the next five-minute move. This is not an oscillator that flashes oversold at market bottoms with convenient precision. COT analysis operates on a timescale measured in weeks and months, revealing positioning shifts that precede major market turns but offer no precision timing. The data arrives three days stale, published only once per week, capturing strategic positioning rather than tactical entries. 
 If you need instant gratification, if you trade intraday moves, if you demand mechanical signals with ninety percent accuracy, close this document now. COT analysis rewards patience, position sizing discipline, and tolerance for being early. It punishes impatience, overleveraging, and the expectation that any single indicator can substitute for market understanding. 
The premise is deceptively simple. Every Tuesday, large traders in futures markets must report their positions to the CFTC. By Friday afternoon, this data becomes public. Academic research spanning three decades has consistently shown that not all market participants are created equal. Some traders consistently profit while others consistently lose. Some anticipate major turning points while others chase trends into exhaustion. Bessembinder and Chan (1992) demonstrated in their seminal study that commercial hedgers, those with actual exposure to the underlying commodity or financial instrument, possess superior forecasting ability compared to speculators. Their research, published in the Journal of Finance, found statistically significant predictive power in commercial positioning, particularly at extreme levels. This finding challenged the efficient market hypothesis and opened the door to a new approach to market analysis based on positioning rather than price alone.
Think about what this means. Every week, the government publishes a report showing you exactly how the most informed market participants are positioned. Not their opinions. Not their predictions. Their actual money at risk. When agricultural producers collectively hold their largest short hedge in five years, they are not making idle speculation. They are locking in prices for crops they will harvest, informed by private knowledge of weather conditions, soil quality, inventory levels, and demand expectations invisible to outside observers. When energy companies aggressively hedge forward production at current prices, they reveal information about expected supply that no analyst report can capture. This is not technical analysis based on past prices. This is not fundamental analysis based on publicly available data. This is behavioral analysis based on how the smartest money is actually positioned, how institutions allocate capital across portfolios, and how those allocation decisions shift as market conditions evolve.
WHY SOME TRADERS KNOW MORE THAN OTHERS
Building on this foundation, Sanders, Boris and Manfredo (2004) conducted extensive research examining the behaviour patterns of different trader categories. Their work, which analyzed over a decade of COT data across multiple commodity markets, revealed a fascinating dynamic that challenges much of what retail traders are taught. Commercial hedgers consistently positioned themselves against market extremes, buying when speculators were most bearish and selling when speculators reached peak bullishness. The contrarian positioning of commercials was not random noise but rather reflected their superior information about supply and demand fundamentals. Meanwhile, large speculators, primarily hedge funds and commodity trading advisors, exhibited strong trend-following behaviour that often amplified market moves beyond fundamental values. Small traders, the retail participants, consistently entered positions late in trends, frequently near turning points, making them reliable contrary indicators.
Wang (2003) extended this research by demonstrating that the predictive power of commercial positioning varies significantly across different commodity sectors. His analysis of agricultural commodities showed particularly strong forecasting ability, with commercial net positions explaining up to fifteen percent of return variance in subsequent weeks. This finding suggests that the informational advantages of hedgers are most pronounced in markets where physical supply and demand fundamentals dominate, as opposed to purely financial markets where information asymmetries are smaller. When a corn farmer hedges six months of expected harvest, that decision incorporates private observations about rainfall patterns, crop health, pest pressure, and local storage capacity that no distant analyst can match. When an oil refinery hedges crude oil purchases and gasoline sales simultaneously, the spread relationships reveal expectations about refining margins that reflect operational realities invisible in public data.
The theoretical mechanism underlying these empirical patterns relates to information asymmetry and different participant motivations. Commercial hedgers engage in futures markets not for speculative profit but to manage business risks. An agricultural producer selling forward six months of expected harvest is not making a bet on price direction but rather locking in revenue to facilitate financial planning and ensure business viability. However, this hedging activity necessarily incorporates private information about expected supply, inventory levels, weather conditions, and demand trends that the hedger observes through their commercial operations (Irwin and Sanders, 2012). When aggregated across many participants, this private information manifests in collective positioning.
Consider a gold mining company deciding how much forward production to hedge. Management must estimate ore grades, recovery rates, production costs, equipment reliability, labor availability, and dozens of other operational variables that determine whether locking in prices at current levels makes business sense. If the industry collectively hedges more aggressively than usual, it suggests either exceptional production expectations or concern about sustaining current price levels or combination of both. Either way, this positioning reveals information unavailable to speculators analyzing price charts and economic data. The hedger sees the physical reality behind the financial abstraction.
Large speculators operate under entirely different incentives and constraints. Commodity Trading Advisors managing billions in assets typically employ systematic, trend-following strategies that respond to price momentum rather than fundamental supply and demand. When crude oil rallies from sixty dollars to seventy dollars per barrel, these systems generate buy signals. As the rally continues to eighty dollars, position sizes increase. The strategy works brilliantly during sustained trends but becomes a liability at reversals. By the time oil reaches ninety dollars, trend-following funds are maximally long, having accumulated positions progressively throughout the rally. At this point, they represent not smart money anticipating further gains but rather crowded money vulnerable to reversal. Sanders, Boris and Manfredo (2004) documented this pattern across multiple energy markets, showing that extreme speculator positioning typically marked late-stage trend exhaustion rather than early-stage trend development.
Small traders, the retail participants who fall below reporting thresholds, display the weakest forecasting ability. Wang (2003) found that small trader positioning exhibited negative correlation with subsequent returns, meaning their aggregate positioning served as a reliable contrary indicator. The explanation combines several factors. Retail traders often lack the capital reserves to weather normal market volatility, leading to premature exits from positions that would eventually prove profitable. They tend to receive information through slower channels, entering trends after mainstream media coverage when institutional participants are preparing to exit. Perhaps most importantly, they trade with emotion, buying into euphoria and selling into panic at precisely the wrong times.
At major turning points, the three groups often position opposite each other with commercials extremely bearish, large speculators extremely bullish, and small traders piling into longs at the last moment. These high-divergence environments frequently precede increased volatility and trend reversals. The insiders with business exposure quietly exit as the momentum traders hit maximum capacity and retail enthusiasm peaks. Within weeks, the reversal begins, and positions unwind in the opposite sequence.
FROM RAW DATA TO ACTIONABLE SIGNALS
The COT Index indicator operationalizes these academic findings into a practical trading tool accessible through TradingView. At its core, the indicator normalizes net positioning data onto a zero to one hundred scale, creating what we call the COT Index. This normalization is critical because absolute position sizes vary dramatically across different futures contracts and over time. A commercial trader holding fifty thousand contracts net long in crude oil might be extremely bullish by historical standards, or it might be quite neutral depending on the context of total market size and historical ranges. Raw position numbers mean nothing without context. The COT Index solves this problem by calculating where current positioning stands relative to its range over a specified lookback period, typically two hundred fifty-two weeks or approximately five years of weekly data.
The mathematical transformation follows the methodology originally popularized by legendary trader Larry Williams, though the underlying concept appears in statistical normalization techniques across many fields. For any given trader category, we calculate the highest and lowest net position values over the lookback period, establishing the historical range for that specific market and trader group. Current positioning is then expressed as a percentage of this range, where zero represents the most bearish positioning ever seen in the lookback window and one hundred represents the most bullish extreme. A reading of fifty indicates positioning exactly in the middle of the historical range, suggesting neither extreme optimism nor pessimism relative to recent history (Williams and Noseworthy, 2009).
This index-based approach allows for meaningful comparison across different markets and time periods, overcoming the scaling problems inherent in analyzing raw position data. A commercial index reading of eighty-five in gold carries the same interpretive meaning as an eighty-five reading in wheat or crude oil, even though the absolute position sizes differ by orders of magnitude. This standardization enables systematic analysis across entire futures portfolios rather than requiring market-specific expertise for each contract.
The lookback period selection involves a fundamental tradeoff between responsiveness and stability. Shorter lookback periods, perhaps one hundred twenty-six weeks or approximately two and a half years, make the index more sensitive to recent positioning changes. However, it also increases noise and produces more false signals. Longer lookback periods, perhaps five hundred weeks or approximately ten years, create smoother readings that filter short-term noise but become slower to recognize regime changes. The indicator settings allow users to adjust this parameter based on their trading timeframe, risk tolerance, and market characteristics.
UNDERSTANDING CFTC DATA STRUCTURES
The indicator supports both Legacy and Disaggregated COT report formats, reflecting the evolution of CFTC reporting standards over decades of market development. Legacy reports categorize market participants into three broad groups: commercial traders (hedgers with underlying business exposure), non-commercial traders (large speculators seeking profit without commercial interest), and non-reportable traders (small speculators below reporting thresholds). Each category brings distinct motivations and information advantages to the market (CFTC, 2020).
The Disaggregated reports, introduced in September 2009 for physical commodity markets, provide finer granularity by splitting participants into five categories (CFTC, 2009). Producer and merchant positions capture those actually producing, processing, or merchandising the physical commodity. Swap dealers represent financial intermediaries facilitating derivative transactions for clients. Managed money includes commodity trading advisors and hedge funds executing systematic or discretionary strategies. Other reportables encompasses diverse participants not fitting the main categories. Small traders remain as the fifth group, representing retail participation.
This enhanced categorization reveals nuances invisible in Legacy reports, particularly distinguishing between different types of institutional capital and their distinct behavioural patterns. The indicator automatically detects which report type is appropriate for each futures contract and adjusts the display accordingly.
Importantly, Disaggregated reports exist only for physical commodity futures. Agricultural commodities like corn, wheat, and soybeans have Disaggregated reports because clear producer, merchant, and swap dealer categories exist. Energy commodities like crude oil and natural gas similarly have well-defined commercial hedger categories. Metals including gold, silver, and copper also receive Disaggregated treatment (CFTC, 2009). However, financial futures such as equity index futures, Treasury bond futures, and currency futures remain available only in Legacy format. The CFTC has indicated no plans to extend Disaggregated reporting to financial futures due to different market structures and participant categories in these instruments (CFTC, 2020).
THE BEHAVIORAL FOUNDATION
Understanding which trader perspective to follow requires appreciation of their distinct trading styles, success rates, and psychological profiles. Commercial hedgers exhibit anticyclical behaviour rooted in their fundamental knowledge and business imperatives. When agricultural producers hedge forward sales during harvest season, they are not speculating on price direction but rather locking in revenue for crops they will harvest. Their business requires converting volatile commodity exposure into predictable cash flows to facilitate planning and ensure survival through difficult periods. Yet their aggregate positioning reveals valuable information because these hedging decisions incorporate private information about supply conditions, inventory levels, weather observations, and demand expectations that hedgers observe through their commercial operations (Bessembinder and Chan, 1992).
Consider a practical example from energy markets. Major oil companies continuously hedge portions of forward production based on price levels, operational costs, and financial planning needs. When crude oil trades at ninety dollars per barrel, they might aggressively hedge the next twelve months of production, locking in prices that provide comfortable profit margins above their extraction costs. This hedging appears as short positioning in COT reports. If oil rallies further to one hundred dollars, they hedge even more aggressively, viewing these prices as exceptional opportunities to secure revenue. Their short positioning grows increasingly extreme. To an outside observer watching only price charts, the rally suggests bullishness. But the commercial positioning reveals that the actual producers of oil find these prices attractive enough to lock in years of sales, suggesting skepticism about sustaining even higher levels. When the eventual reversal occurs and oil declines back to eighty dollars, the commercials who hedged at ninety and one hundred dollars profit while speculators who chased the rally suffer losses.
Large speculators or managed money traders operate under entirely different incentives and constraints. Their systematic, momentum-driven strategies mean they amplify existing trends rather than anticipate reversals. Trend-following systems, the most common approach among large speculators, by definition require confirmation of trend through price momentum before entering positions (Sanders, Boris and Manfredo, 2004). When crude oil rallies from sixty dollars to eighty dollars per barrel over several months, trend-following algorithms generate buy signals based on moving average crossovers, breakouts, and other momentum indicators. As the rally continues, position sizes increase according to the systematic rules.
However, this approach becomes a liability at turning points. By the time oil reaches ninety dollars after a sustained rally, trend-following funds are maximally long, having accumulated positions progressively throughout the move. At this point, their positioning does not predict continued strength. Rather, it often marks late-stage trend exhaustion. The psychological and mechanical explanation is straightforward. Trend followers by definition chase price momentum, entering positions after trends establish rather than anticipating them. Eventually, they become fully invested just as the trend nears completion, leaving no incremental buying power to sustain the rally. When the first signs of reversal appear, systematic stops trigger, creating a cascade of selling that accelerates the downturn.
Small traders consistently display the weakest track record across academic studies. Wang (2003) found that small trader positioning exhibited negative correlation with subsequent returns in his analysis across multiple commodity markets. This result means that whatever small traders collectively do, the opposite typically proves profitable. The explanation for small trader underperformance combines several factors documented in behavioral finance literature. Retail traders often lack the capital reserves to weather normal market volatility, leading to premature exits from positions that would eventually prove profitable. They tend to receive information through slower channels, learning about commodity trends through mainstream media coverage that arrives after institutional participants have already positioned. Perhaps most importantly, retail traders are more susceptible to emotional decision-making, buying into euphoria and selling into panic at precisely the wrong times (Tharp, 2008).
SETTINGS, THRESHOLDS, AND SIGNAL GENERATION
The practical implementation of the COT Index requires understanding several key features and settings that users can adjust to match their trading style, timeframe, and risk tolerance. The lookback period determines the time window for calculating historical ranges. The default setting of two hundred fifty-two bars represents approximately one year on daily charts or five years on weekly charts, balancing responsiveness with stability. Conservative traders seeking only the most extreme, highest-probability signals might extend the lookback to five hundred bars or more. Aggressive traders seeking earlier entry and willing to accept more false positives might reduce it to one hundred twenty-six bars or even less for shorter-term applications.
The bullish and bearish thresholds define signal generation levels. Default settings of eighty and twenty respectively reflect academic research suggesting meaningful information content at these extremes. Readings above eighty indicate positioning in the top quintile of the historical range, representing genuine extremes rather than temporary fluctuations. Conversely, readings below twenty occupy the bottom quintile, indicating unusually bearish positioning (Briese, 2008).
However, traders must recognize that appropriate thresholds vary by market, trader category, and personal risk tolerance. Some futures markets exhibit wider positioning swings than others due to seasonal patterns, volatility characteristics, or participant behavior. Conservative traders seeking high-probability setups with fewer signals might raise thresholds to eighty-five and fifteen. Aggressive traders willing to accept more false positives for earlier entry could lower them to seventy-five and twenty-five.
The key is maintaining meaningful differentiation between bullish, neutral, and bearish zones. The default settings of eighty and twenty create a clear three-zone structure. Readings from zero to twenty represent bearish territory where the selected trader group holds unusually bearish positions. Readings from twenty to eighty represent neutral territory where positioning falls within normal historical ranges. Readings from eighty to one hundred represent bullish territory where the selected trader group holds unusually bullish positions.
The trading perspective selection determines which participant group the indicator follows, fundamentally shaping interpretation and signal meaning. For counter-trend traders seeking reversal opportunities, monitoring commercial positioning makes intuitive sense based on the academic research discussed earlier. When commercials reach extreme bearish readings below twenty, indicating unprecedented short positioning relative to recent history, they are effectively betting against the crowd. Given their informational advantages demonstrated by Bessembinder and Chan (1992), this contrarian stance often precedes major bottoms.
Trend followers might instead monitor large speculator positioning, but with inverted logic compared to commercials. When managed money reaches extreme bullish readings above eighty, the trend may be exhausting rather than accelerating. This seeming paradox reflects their late-cycle participation documented by Sanders, Boris and Manfredo (2004). Sophisticated traders thus use speculator extremes as fade signals, entering positions opposite to speculator consensus.
Small trader monitoring serves primarily as a contrary indicator for all trading styles. Extreme small trader bullishness above seventy-five or eighty typically warns of retail FOMO at market tops. Extreme small trader bearishness below twenty or twenty-five often marks capitulation bottoms where the last weak hands have sold.
VISUALIZATION AND USER INTERFACE
The visual design incorporates multiple elements working together to facilitate decision-making and maintain situational awareness during active trading. The primary COT Index line plots in bold with adjustable line width, defaulting to two pixels for clear visibility against busy price charts. An optional glow effect, controlled by a simple toggle, adds additional visual prominence through multiple plot layers with progressively increasing transparency and width.
A twenty-one period exponential moving average overlays the index line, providing trend context for positioning changes. When the index crosses above its moving average, it signals accelerating bullish sentiment among the selected trader group regardless of whether absolute positioning is extreme. Conversely, when the index crosses below its moving average, it signals deteriorating sentiment and potentially the beginning of a reversal in positioning trends.
The EMA provides a dynamic reference line for assessing positioning momentum. When the index trades far above its EMA, positioning is not only extreme in absolute terms but also building with momentum. When the index trades far below its EMA, positioning is contracting or reversing, which may indicate weakening conviction even if absolute levels remain elevated.
The data table positioned at the top right of the chart displays eleven metrics for each trader category, transforming the indicator from a simple index calculation into an analytical dashboard providing multidimensional market intelligence. Beyond the COT Index itself, users can monitor positioning extremity, which measures how unusual current levels are compared to historical norms using statistical techniques. The extremity metric clarifies whether a reading represents the ninety-fifth or ninety-ninth percentile, with values above two standard deviations indicating genuinely exceptional positioning.
Market power quantifies each group's influence on total open interest. This metric expresses each trader category's net position as a percentage of total market open interest. A commercial entity holding forty percent of total open interest commands significantly more influence than one holding five percent, making their positioning signals more meaningful.
Momentum and rate of change metrics reveal whether positions are building or contracting, providing early warning of potential regime shifts. Position velocity measures the rate of change in positioning changes, effectively a second derivative providing even earlier insight into inflection points.
Sentiment divergence highlights disagreements between commercial and speculative positioning. This metric calculates the absolute difference between normalized commercial and large speculator index values. Wang (2003) found that these high-divergence environments frequently preceded increased volatility and reversals.
The table also displays concentration metrics when available, showing how positioning is distributed among the largest handful of traders in each category. High concentration indicates a few dominant players controlling most of the positioning, while low concentration suggests broad-based participation across many traders.
THE ALERT SYSTEM AND MONITORING
The alert system, comprising five distinct alert conditions, enables systematic monitoring of dozens of futures markets without constant screen watching. The bullish and bearish COT signal alerts trigger when the index crosses user-defined thresholds, indicating the selected trader group has reached extreme positioning worthy of attention. These alerts fire in real-time as new weekly COT data publishes, typically Friday afternoon following the Tuesday measurement date.
Extreme positioning alerts fire at ninety and ten index levels, representing the top and bottom ten percent of the historical range, warning of particularly stretched readings that historically precede reversals with high probability. When commercials reach a COT Index reading below ten, they are expressing their most bearish stance in the entire lookback period.
The data staleness alert notifies users when COT reports have not updated for more than ten days, preventing reliance on outdated information for trading decisions. Government shutdowns or federal holidays can interrupt the normal Friday publication schedule. Using stale signals while believing them current creates dangerous false confidence.
The indicator's watermark information display positioned in the bottom right corner provides essential context at a glance. This persistent display shows the symbol and timeframe, the COT report date timestamp, days since last update, and the current signal state. A trader analyzing a potential short entry in crude oil can glance at the watermark to instantly confirm positioning context without interrupting analysis flow.
LIMITATIONS AND REALISTIC EXPECTATIONS
Practical application requires understanding both the indicator's considerable strengths and inherent limitations. COT data inherently lags price action by three days, as Tuesday positions are not published until Friday afternoon. This delay means the indicator cannot catch rapid intraday reversals or respond to surprise news events. Traders using the COT Index for timing entries must accept this latency and focus on swing trading and position trading timeframes where three-day lags matter less than in day trading or scalping.
The weekly publication schedule similarly makes the indicator unsuitable for short-term trading strategies requiring immediate feedback. The COT Index works best for traders operating on weekly or longer timeframes, where positioning shifts measured in weeks and months align with trading horizon.
Extreme COT readings can persist far longer than typical technical indicators suggest, testing the patience and capital reserves of traders attempting to fade them. When crude oil enters a sustained bull market driven by genuine supply disruptions, commercial hedgers may maintain bearish positioning for many months as prices grind higher. A commercial COT Index reading of fifteen indicating extreme bearishness might persist for three months while prices continue rallying before finally reversing. Traders without sufficient capital and risk tolerance to weather such drawdowns will exit prematurely, precisely when the signal is about to work (Irwin and Sanders, 2012).
Position sizing discipline becomes paramount when implementing COT-based strategies. Rather than risking large percentages of capital on individual signals, successful COT traders typically allocate modest position sizes across multiple signals, allowing some to take time to mature while others work more quickly.
The indicator also cannot overcome fundamental regime changes that alter the structural drivers of markets. If gold enters a true secular bull market driven by monetary debasement, commercial hedgers may remain persistently bearish as mining companies sell forward years of production at what they perceive as favorable prices. Their positioning indicates valuation concerns from a production cost perspective, but cannot stop prices from rising if investment demand overwhelms physical supply-demand balance.
Similarly, structural changes in market participation can alter the meaning of positioning extremes. The growth of commodity index investing in the two thousands brought massive passive long-only capital into futures markets, fundamentally changing typical positioning ranges. Traders relying on COT signals without recognizing this regime change would have generated numerous false bearish signals during the commodity supercycle from 2003 to 2008.
The research foundation supporting COT analysis derives primarily from commodity markets where the commercial hedger information advantage is most pronounced. Studies specifically examining financial futures like equity indices and bonds show weaker but still present effects. Traders should calibrate expectations accordingly, recognizing that COT analysis likely works better for crude oil, natural gas, corn, and wheat than for the S&P 500, Treasury bonds, or currency futures.
Another important limitation involves the reporting threshold structure. Not all market participants appear in COT data, only those holding positions above specified minimums. In markets dominated by a few large players, concentration metrics become critical for proper interpretation. A single large trader accounting for thirty percent of commercial positioning might skew the entire category if their individual circumstances are idiosyncratic rather than representative.
GOLD FUTURES DURING A HYPOTHETICAL MARKET CYCLE
Consider a practical example using gold futures during a hypothetical but realistic market scenario that illustrates how the COT Index indicator guides trading decisions through a complete market cycle. Suppose gold has rallied from fifteen hundred to nineteen hundred dollars per ounce over six months, driven by inflation concerns following aggressive monetary expansion, geopolitical uncertainty, and sustained buying by Asian central banks for reserve diversification.
Large speculators, operating primarily trend-following strategies, have accumulated increasingly bullish positions throughout this rally. Their COT Index has climbed progressively from forty-five to eighty-five. The table display shows that large speculators now hold net long positions representing thirty-two percent of total open interest, their highest in four years. Momentum indicators show positive readings, indicating positions are still building though at a decelerating rate. Position velocity has turned negative, suggesting the pace of position building is slowing.
Meanwhile, commercial hedgers have responded to the rally by aggressively selling forward production and inventory. Their COT Index has moved inversely to price, declining from fifty-five to twenty. This bearish commercial positioning represents mining companies locking in forward sales at prices they view as attractive relative to production costs. The table shows commercials now hold net short positions representing twenty-nine percent of total open interest, their most bearish stance in five years. Concentration metrics indicate this positioning is broadly distributed across many commercial entities, suggesting the bearish stance reflects collective industry view rather than idiosyncratic positioning by a single firm.
Small traders, attracted by mainstream financial media coverage of gold's impressive rally, have recently piled into long positions. Their COT Index has jumped from forty-five to seventy-eight as retail investors chase the trend. Television financial networks feature frequent segments on gold with bullish guests. Internet forums and social media show surging retail interest. This retail enthusiasm historically marks late-stage trend development rather than early opportunity.
The COT Index indicator, configured to monitor commercial positioning from a contrarian perspective, displays a clear bearish signal given the extreme commercial short positioning. The table displays multiple confirming metrics: positioning extremity shows commercials at the ninety-sixth percentile of bearishness, market power indicates they control twenty-nine percent of open interest, and sentiment divergence registers sixty-five, indicating massive disagreement between commercial hedgers and large speculators. This divergence, the highest in three years, places the market in the historically high-risk category for reversals.
The interpretation requires nuance and consideration of context beyond just COT data. Commercials are not necessarily predicting an imminent crash. Rather, they are hedging business operations at what they collectively view as favorable price levels. However, the data reveals they have sold unusually large quantities of forward production, suggesting either exceptional production expectations for the year ahead or concern about sustaining current price levels or combination of both. Combined with extreme speculator positioning indicating a crowded long trade, and small trader enthusiasm confirming retail FOMO, the confluence suggests elevated reversal risk even if the precise timing remains uncertain.
A prudent trader analyzing this situation might take several actions based on COT Index signals. Existing long positions could be tightened with closer stop losses. Profit-taking on a portion of long exposure could lock in gains while maintaining some participation. Some traders might initiate modest short positions as portfolio hedges, sizing them appropriately for the inherent uncertainty in timing reversals. Others might simply move to the sidelines, avoiding new long entries until positioning normalizes.
The key lesson from case study analysis is that COT signals provide probabilistic edges rather than deterministic predictions. They work over many observations by identifying higher-probability configurations, not by generating perfect calls on individual trades. A fifty-five percent win rate with proper risk management produces substantial profits over time, yet still means forty-five percent of signals will be premature or wrong. Traders must embrace this probabilistic reality rather than seeking the impossible goal of perfect accuracy.
INTEGRATION WITH TRADING SYSTEMS
Integration with existing trading systems represents a natural and powerful use case for COT analysis, adding a positioning dimension to price-based technical approaches or fundamental analytical frameworks. Few traders rely exclusively on a single indicator or methodology. Rather, they build systems that synthesize multiple information sources, with each component addressing different aspects of market behavior.
Trend followers might use COT extremes as regime filters, modifying position sizing or avoiding new trend entries when positioning reaches levels historically associated with reversals. Consider a classic trend-following system based on moving average crossovers and momentum breakouts. Integration of COT analysis adds nuance. When large speculator positioning exceeds ninety or commercial positioning falls below ten, the regime filter recognizes elevated reversal risk. The system might reduce position sizing by fifty percent for new signals during these high-risk periods (Kaufman, 2013).
Mean reversion traders might require COT signal confluence before fading extended moves. When crude oil becomes technically overbought and large speculators show extreme long positioning above eighty-five, both signals confirm. If only technical indicators show extremes while positioning remains neutral, the potential short signal is rejected, avoiding fades of trends with underlying institutional support (Kaufman, 2013).
Discretionary traders can monitor the indicator as a continuous awareness tool, informing bias and position sizing without dictating mechanical entries and exits. A discretionary trader might notice commercial positioning shifting from neutral to progressively more bullish over several months. This trend informs growing positive bias even without triggering mechanical signals.
Multi-timeframe analysis represents another powerful integration approach. A trader might use daily charts for trade execution and timing while monitoring weekly COT positioning for strategic context. When both timeframes align, highest-probability opportunities emerge.
Portfolio construction for futures traders can incorporate COT signals as an additional selection criterion. Markets showing strong technical setups AND favorable COT positioning receive highest allocations. Markets with strong technicals but neutral or unfavorable positioning receive reduced allocations.
ADVANCED METRICS AND INTERPRETATION
The metrics table transforms simple positioning data into multidimensional market intelligence. Position extremity, calculated as the absolute deviation from the historical mean normalized by standard deviation, helps identify truly unusual readings versus routine fluctuations. A reading above two standard deviations indicates ninety-fifth percentile or higher extremity. Above three standard deviations indicates ninety-ninth percentile or higher, genuinely rare positioning that historically precedes major events with high probability.
Market power, expressed as a percentage of total open interest, reveals whose positioning matters most from a mechanical market impact perspective. Consider two scenarios in gold futures. In scenario one, commercials show a COT Index reading of fifteen while their market power metric shows they hold net shorts representing thirty-five percent of open interest. This is a high-confidence bearish signal. In scenario two, commercials also show a reading of fifteen, but market power shows only eight percent. While positioning is extreme relative to this category's normal range, their limited market share means less mechanical influence on price.
The rate of change and momentum metrics highlight whether positions are accelerating or decelerating, often providing earlier warnings than absolute levels alone. A COT Index reading of seventy-five with rapidly building momentum suggests continued movement toward extremes. Conversely, a reading of eighty-five with decelerating or negative momentum indicates the positioning trend is exhausting.
Position velocity measures the rate of change in positioning changes, effectively a second derivative. When velocity shifts from positive to negative, it indicates that while positioning may still be growing, the pace of growth is slowing. This deceleration often precedes actual reversal in positioning direction by several weeks.
Sentiment divergence calculates the absolute difference between normalized commercial and large speculator index values. When commercials show extreme bearish positioning at twenty while large speculators show extreme bullish positioning at eighty, the divergence reaches sixty, representing near-maximum disagreement. Wang (2003) found that these high-divergence environments frequently preceded increased volatility and reversals. The mechanism is intuitive. Extreme divergence indicates the informed hedgers and momentum-following speculators have positioned opposite each other with conviction. One group will prove correct and profit while the other proves incorrect and suffers losses. The resolution of this disagreement through price movement often involves volatility.
The table also displays concentration metrics when available. High concentration indicates a few dominant players controlling most of the positioning within a category, while low concentration suggests broad-based participation. Broad-based positioning more reliably reflects collective market intelligence and industry consensus. If mining companies globally all independently decide to hedge aggressively at similar price levels, it suggests genuine industry-wide view about price valuations rather than circumstances specific to one firm.
DATA QUALITY AND RELIABILITY
The CFTC has maintained COT reporting in various forms since the nineteen twenties, providing nearly a century of positioning data across multiple market cycles. However, data quality and reporting standards have evolved substantially over this long period. Modern electronic reporting implemented in the late nineteen nineties and early two thousands significantly improved accuracy and timeliness compared to earlier paper-based systems.
Traders should understand that COT reports capture positions as of Tuesday's close each week. Markets remain open three additional days before publication on Friday afternoon, meaning the reported data is three days stale when received. During periods of rapid market movement or major news events, this lag can be significant. The indicator addresses this limitation by including timestamp information and staleness warnings.
The three-day lag creates particular challenges during extreme volatility episodes. Flash crashes, surprise central bank interventions, geopolitical shocks, and other high-impact events can completely transform market positioning within hours. Traders must exercise judgment about whether reported positioning remains relevant given intervening events.
Reporting thresholds also mean that not all market participants appear in disaggregated COT data. Traders holding positions below specified minimums aggregate into the non-reportable or small trader category. This aggregation affects different markets differently. In highly liquid contracts like crude oil with thousands of participants, reportable traders might represent seventy to eighty percent of open interest. In thinly traded contracts with only dozens of active participants, a few large reportable positions might represent ninety-five percent of open interest.
Another data quality consideration involves trader classification into categories. The CFTC assigns traders to commercial or non-commercial categories based on reported business purpose and activities. However, this process is not perfect. Some entities engage in both commercial and speculative activities, creating ambiguity about proper classification. The transition to Disaggregated reports attempted to address some of these ambiguities by creating more granular categories.
COMPARISON WITH ALTERNATIVE APPROACHES
Several alternative approaches to COT analysis exist in the trading community beyond the normalization methodology employed by this indicator. Some analysts focus on absolute position changes week-over-week rather than index-based normalization. This approach calculates the change in net positioning from one week to the next. The emphasis falls on momentum in positioning changes rather than absolute levels relative to history. This method potentially identifies regime shifts earlier but sacrifices cross-market comparability (Briese, 2008).
Other practitioners employ more complex statistical transformations including percentile rankings, z-score standardization, and machine learning classification algorithms. Ruan and Zhang (2018) demonstrated that machine learning models applied to COT data could achieve modest improvements in forecasting accuracy compared to simple threshold-based approaches. However, these gains came at the cost of interpretability and implementation complexity.
The COT Index indicator intentionally employs a relatively straightforward normalization methodology for several important reasons. First, transparency enhances user understanding and trust. Traders can verify calculations manually and develop intuitive feel for what different readings mean. Second, academic research suggests that most of the predictive power in COT data comes from extreme positioning levels rather than subtle patterns requiring complex statistical methods to detect. Third, robust methods that work consistently across many markets and time periods tend to be simpler rather than more complex, reducing the risk of overfitting to historical data. Fourth, the complexity costs of implementation matter for retail traders without programming teams or computational infrastructure.
PSYCHOLOGICAL ASPECTS OF COT TRADING
Trading based on COT data requires psychological fortitude that differs from momentum-based approaches. Contrarian positioning signals inherently mean betting against prevailing market sentiment and recent price action. When commercials reach extreme bearish positioning, prices have typically been rising, sometimes for extended periods. The price chart looks bullish, momentum indicators confirm strength, moving averages align positively. The COT signal says bet against all of this. This psychological difficulty explains why COT analysis remains underutilized relative to trend-following methods.
Human psychology strongly predisposes us toward extrapolation and recency bias. When prices rally for months, our pattern-matching brains naturally expect continued rally. The recent price action dominates our perception, overwhelming rational analysis about positioning extremes and historical probabilities. The COT signal asking us to sell requires overriding these powerful psychological impulses.
The indicator design attempts to support the required psychological discipline through several features. Clear threshold markers and signal states reduce ambiguity about when signals trigger. When the commercial index crosses below twenty, the signal is explicit and unambiguous. The background shifts to red, the signal label displays bearish, and alerts fire. This explicitness helps traders act on signals rather than waiting for additional confirmation that may never arrive.
The metrics table provides analytical justification for contrarian positions, helping traders maintain conviction during inevitable periods of adverse price movement. When a trader enters short positions based on extreme commercial bearish positioning but prices continue rallying for several weeks, doubt naturally emerges. The table display provides reassurance. Commercial positioning remains extremely bearish. Divergence remains high. The positioning thesis remains intact even though price action has not yet confirmed.
Alert functionality ensures traders do not miss signals due to inattention while also not requiring constant monitoring that can lead to emotional decision-making. Setting alerts for COT extremes enables a healthier relationship with markets. When meaningful signals occur, alerts notify them. They can then calmly assess the situation and execute planned responses.
However, no indicator design can completely overcome the psychological difficulty of contrarian trading. Some traders simply cannot maintain short positions while prices rally. For these traders, COT analysis might be better employed as an exit signal for long positions rather than an entry signal for shorts.
Ultimately, successful COT trading requires developing comfort with probabilistic thinking rather than certainty-seeking. The signals work over many observations by identifying higher-probability configurations, not by generating perfect calls on individual trades. A fifty-five or sixty percent win rate with proper risk management produces substantial profits over years, yet still means forty to forty-five percent of signals will be premature or wrong. COT analysis provides genuine edge, but edge means probability advantage, not elimination of losing trades.
EDUCATIONAL RESOURCES AND CONTINUOUS LEARNING
The indicator provides extensive built-in educational resources through its documentation, detailed tooltips, and transparent calculations. However, mastering COT analysis requires study beyond any single tool or resource. Several excellent resources provide valuable extensions of the concepts covered in this guide.
Books and practitioner-focused monographs offer accessible entry points. Stephen Briese published The Commitments of Traders Bible in two thousand eight, offering detailed breakdowns of how different markets and trader categories behave (Briese, 2008). Briese's work stands out for its empirical focus and market-specific insights. Jack Schwager includes discussion of COT analysis within the broader context of market behavior in his book Market Sense and Nonsense (Schwager, 2012). Perry Kaufman's Trading Systems and Methods represents perhaps the most rigorous practitioner-focused text on systematic trading approaches including COT analysis (Kaufman, 2013).
Academic journal articles provide the rigorous statistical foundation underlying COT analysis. The Journal of Futures Markets regularly publishes research on positioning data and its predictive properties. Bessembinder and Chan's earlier work on systematic risk, hedging pressure, and risk premiums in futures markets provides theoretical foundation (Bessembinder, 1992). Chang's examination of speculator returns provides historical context (Chang, 1985). Irwin and Sanders provide essential skeptical perspective in their two thousand twelve article (Irwin and Sanders, 2012). Wang's two thousand three article provides one of the most empirical analyses of COT data across multiple commodity markets (Wang, 2003).
Online resources extend beyond academic and book-length treatments. The CFTC website provides free access to current and historical COT reports in multiple formats. The explanatory materials section offers detailed documentation of report construction, category definitions, and historical methodology changes. Traders serious about COT analysis should read these official CFTC documents to understand exactly what they are analyzing.
Commercial COT data services such as Barchart provide enhanced visualization and analysis tools beyond raw CFTC data. TradingView's educational materials, published scripts library, and user community provide additional resources for exploring different approaches to COT analysis.
The key to mastering COT analysis lies not in finding a single definitive source but rather in building understanding through multiple perspectives and information sources. Academic research provides rigorous empirical foundation. Practitioner-focused books offer practical implementation insights. Direct engagement with data through systematic backtesting develops intuition about how positioning dynamics manifest across different market conditions.
SYNTHESIZING KNOWLEDGE INTO PRACTICE
The COT Index indicator represents the synthesis of academic research, trading experience, and software engineering into a practical tool accessible to retail traders equipped with nothing more than a TradingView account and willingness to learn. What once required expensive data subscriptions, custom programming capabilities, statistical software, and institutional resources now appears as a straightforward indicator requiring only basic parameter selection and modest study to understand. This democratization of institutional-grade analysis tools represents a broader trend in financial markets over recent decades.
Yet technology and data access alone provide no edge without understanding and discipline. Markets remain relentlessly efficient at eliminating edges that become too widely known and mechanically exploited. The COT Index indicator succeeds only when users invest time learning the underlying concepts, understand the limitations and probability distributions involved, and integrate signals thoughtfully into trading plans rather than applying them mechanically.
The academic research demonstrates conclusively that institutional positioning contains genuine information about future price movements, particularly at extremes where commercial hedgers are maximally bearish or bullish relative to historical norms. This informational content is neither perfect nor deterministic but rather probabilistic, providing edge over many observations through identification of higher-probability configurations. Bessembinder and Chan's finding that commercial positioning explained modest but significant variance in future returns illustrates this probabilistic nature perfectly (Bessembinder and Chan, 1992). The effect is real and statistically significant, yet it explains perhaps ten to fifteen percent of return variance rather than most variance. Much of price movement remains unpredictable even with positioning intelligence.
The practical implication is that COT analysis works best as one component of a trading system rather than a standalone oracle. It provides the positioning dimension, revealing where the smart money has positioned and where the crowd has followed, but price action analysis provides the timing dimension. Fundamental analysis provides the catalyst dimension. Risk management provides the survival dimension. These components work together synergistically.
The indicator's design philosophy prioritizes transparency and education over black-box complexity, empowering traders to understand exactly what they are analyzing and why. Every calculation is documented and user-adjustable. The threshold markers, background coloring, tables, and clear signal states provide multiple reinforcing channels for conveying the same information.
This educational approach reflects a conviction that sustainable trading success comes from genuine understanding rather than mechanical system-following. Traders who understand why commercial positioning matters, how different trader categories behave, what positioning extremes signify, and where signals fit within probability distributions can adapt when market conditions change. Traders mechanically following black-box signals without comprehension abandon systems after normal losing streaks.
The research foundation supporting COT analysis comes primarily from commodity markets where commercial hedger informational advantages are most pronounced. Agricultural producers hedging crops know more about supply conditions than distant speculators. Energy companies hedging production know more about operating costs than financial traders. Metals miners hedging output know more about ore grades than index funds. Financial futures markets show weaker but still present effects.
The journey from reading this documentation to profitable trading based on COT analysis involves several stages that cannot be rushed. Initial reading and basic understanding represents the first stage. Historical study represents the second stage, reviewing past market cycles to observe how positioning extremes preceded major turning points. Paper trading or small-size real trading represents the third stage to experience the psychological challenges. Refinement based on results and personal psychology represents the fourth stage.
Markets will continue evolving. New participant categories will emerge. Regulatory structures will change. Technology will advance. Yet the fundamental dynamics driving COT analysis, that different market participants have different information, different motivations, and different forecasting abilities that manifest in their positioning, will persist as long as futures markets exist. While specific thresholds or optimal parameters may shift over time, the core logic remains sound and adaptable.
The trader equipped with this indicator, understanding of the theory and evidence behind COT analysis, realistic expectations about probability rather than certainty, discipline to maintain positions through adverse volatility, and patience to allow signals time to develop possesses genuine edge in markets. The edge is not enormous, markets cannot allow large persistent inefficiencies without arbitraging them away, but it is real, measurable, and exploitable by those willing to invest in learning and disciplined application.
REFERENCES
Bessembinder, H. (1992) Systematic risk, hedging pressure, and risk premiums in futures markets, Review of Financial Studies, 5(4), pp. 637-667.
Bessembinder, H. and Chan, K. (1992) The profitability of technical trading rules in the Asian stock markets, Pacific-Basin Finance Journal, 3(2-3), pp. 257-284.
Briese, S. (2008) The Commitments of Traders Bible: How to Profit from Insider Market Intelligence. Hoboken: John Wiley & Sons.
Chang, E.C. (1985) Returns to speculators and the theory of normal backwardation, Journal of Finance, 40(1), pp. 193-208.
Commodity Futures Trading Commission (CFTC) (2009) Explanatory Notes: Disaggregated Commitments of Traders Report. Available at: www.cftc.gov (Accessed: 15 January 2025).
Commodity Futures Trading Commission (CFTC) (2020) Commitments of Traders: About the Report. Available at: www.cftc.gov (Accessed: 15 January 2025).
Irwin, S.H. and Sanders, D.R. (2012) Testing the Masters Hypothesis in commodity futures markets, Energy Economics, 34(1), pp. 256-269.
Kaufman, P.J. (2013) Trading Systems and Methods. 5th edn. Hoboken: John Wiley & Sons.
Ruan, Y. and Zhang, Y. (2018) Forecasting commodity futures prices using machine learning: Evidence from the Chinese commodity futures market, Applied Economics Letters, 25(12), pp. 845-849.
Sanders, D.R., Boris, K. and Manfredo, M. (2004) Hedgers, funds, and small speculators in the energy futures markets: an analysis of the CFTC's Commitments of Traders reports, Energy Economics, 26(3), pp. 425-445.
Schwager, J.D. (2012) Market Sense and Nonsense: How the Markets Really Work and How They Don't. Hoboken: John Wiley & Sons.
Tharp, V.K. (2008) Super Trader: Make Consistent Profits in Good and Bad Markets. New York: McGraw-Hill.
Wang, C. (2003) The behavior and performance of major types of futures traders, Journal of Futures Markets, 23(1), pp. 1-31.
Williams, L.R. and Noseworthy, M. (2009) The Right Stock at the Right Time: Prospering in the Coming Good Years. Hoboken: John Wiley & Sons.
FURTHER READING
For traders seeking to deepen their understanding of COT analysis and futures market positioning beyond this documentation, the following resources provide valuable extensions:
Academic Journal Articles:
Fishe, R.P.H. and Smith, A. (2012) Do speculators drive commodity prices away from supply and demand fundamentals?, Journal of Commodity Markets, 1(1), pp. 1-16.
Haigh, M.S., Hranaiova, J. and Overdahl, J.A. (2007) Hedge funds, volatility, and liquidity provision in energy futures markets, Journal of Alternative Investments, 9(4), pp. 10-38.
Kocagil, A.E. (1997) Does futures speculation stabilize spot prices? Evidence from metals markets, Applied Financial Economics, 7(1), pp. 115-125.
Sanders, D.R. and Irwin, S.H. (2011) The impact of index funds in commodity futures markets: A systems approach, Journal of Alternative Investments, 14(1), pp. 40-49.
Books and Practitioner Resources:
Murphy, J.J. (1999) Technical Analysis of the Financial Markets: A Guide to Trading Methods and Applications. New York: New York Institute of Finance.
Pring, M.J. (2002) Technical Analysis Explained: The Investor's Guide to Spotting Investment Trends and Turning Points. 4th edn. New York: McGraw-Hill.
Federal Reserve and Research Institution Publications:
Federal Reserve Banks regularly publish working papers examining commodity markets, futures positioning, and price discovery mechanisms. The Federal Reserve Bank of San Francisco and Federal Reserve Bank of Kansas City maintain active research programs in this area.
Online Resources:
The CFTC website provides free access to current and historical COT reports, explanatory materials, and regulatory documentation.
Barchart offers enhanced COT data visualization and screening tools.
TradingView's community library contains numerous published scripts and educational materials exploring different approaches to positioning analysis.
Momentum Master v1Momentum Master v1 - Advanced Multi-Filter Confluence Trading System
### Technical Methodology
Multi-timeframe EMA crossover system with institutional flow analysis, proprietary Fair Value Gap (FVG) retracement detection, and Point of Control (POC) proximity filtering.
The script combines six distinct confirmation filters: customizable EMA crossover signals (3/21 default), RSI momentum analysis (14-period), proprietary FVG retracement algorithm with 200-bar lookback, multi-timeframe POC proximity calculation (Volume/Session/Daily/Weekly), institutional order block detection with retest confirmation, and adaptive ATR-based risk management with real-time confidence scoring.
### Unique Features
1. **Proprietary FVG Retracement Algorithm** - Advanced institutional flow analysis with 200-bar lookback and 20% ATR tolerance
2. **Multi-Timeframe POC Confluence System** - Combines 4 different POC calculations (Volume Profile 30-bar, Session, Daily, Weekly) for key level analysis
3. **Adaptive Confidence Scoring System** - Dynamic risk management based on signal quality (0-100%) with real-time performance tracking
4. **Advanced Performance Analytics** - Real-time win/loss statistics for each TP level with up to 500 individual trade verification labels
5. **Professional Risk Management** - Six-level take-profit system (2:1, 4:1, 6:1, 8:1, 10:1, 12:1) with ATR-based stops
### How It Works
**Entry Requirements:** Fast EMA (3) crosses above Slow EMA (21) + RSI < 70 + volume > 1.1x average + FVG retracement confirmation + POC proximity within 2.0x ATR + order block direction alignment.
**Risk Management:** ATR-based stop loss placement with 1.0x multiplier. Six take-profit levels at 2:1, 4:1, 6:1, 8:1, 10:1, and 12:1 risk/reward ratios.
**Performance Tracking:** Real-time win/loss statistics with up to 500 individual trade labels for verification, confidence scoring system, and comprehensive performance analytics for each TP level.
### Value Proposition
This script combines 6 different institutional flow analysis techniques that would require multiple free scripts to replicate. The proprietary FVG retracement algorithm, multi-timeframe POC analysis, and adaptive confidence scoring system are not available in any single free script.
### Use Cases
- **Best Timeframes:** 5-minute for scalping, 15-minute for swing trades
- **Suitable Markets:** Forex major pairs, Crypto, major indices
- **Market Conditions:** Trending markets with high volume sessions
### Access Instructions
To request access to this invite-only script:
- **Contact:** with your TradingView username
- **Requirements:** Include your TradingView username and brief trading experience
- **Process:** I will review requests within 24 hours and grant access to qualified traders
---
### Technical Justification for Indicator Combination
**Why These Indicators Work Together:**
This script combines 6 distinct analysis methods because each serves a specific purpose in the signal generation pipeline. The EMA crossover provides trend direction, RSI prevents entries in extreme zones, volume confirms institutional participation, FVG retracement validates institutional flow, POC proximity ensures key level alignment, and order block detection confirms institutional context.
**Component Integration Logic:**
- **EMA Crossover (3/21 customizable):** Primary trend detection mechanism with multiple speed options (Standard 9/21, Fast 7/17, Slow 13/26, Custom)
- **RSI Filter (14-period):** Momentum validation to avoid extreme overbought/oversold entries
- **Volume Analysis (1.1x threshold):** Institutional participation confirmation with trend analysis
- **FVG Retracement (200-bar lookback):** Validates price action within institutional flow zones
- **Multi-Timeframe POC (Volume/Session/Daily/Weekly):** Ensures confluence with key price levels
- **Order Block Detection:** Confirms institutional accumulation/distribution context
### Detailed Functionality Explanation
**What This Script Does:**
Generates high-probability momentum scalping signals with multiple take-profit levels and adaptive risk management. The script analyzes price action across multiple timeframes to identify optimal entry points where institutional flow, key levels, and momentum align.
**How It Works:**
1. **Signal Generation:** EMA crossover triggers base signal
2. **Filter Validation:** Six confirmation filters validate signal quality
3. **Confidence Scoring:** Dynamic scoring system rates signal strength (0-100%)
4. **Risk Management:** ATR-based stops with adaptive sizing based on confidence
5. **Profit Taking:** Six-level TP system with fixed risk/reward ratios
6. **Performance Tracking:** Real-time win/loss statistics with trade verification
**How to Use It:**
- **Timeframes:** 5m for scalping, 15m for swing trades, 1h for position entries
- **Markets:** Forex majors, Crypto, major indices
- **Setup:** Apply to chart, configure filters, set risk parameters, monitor confidence scores
- **Entry:** Wait for all filters to align, enter on signal confirmation
- **Exit:** Use ATR-based stops and multiple TP levels
### Originality and Unique Features
**Proprietary Algorithms:**
1. **Advanced FVG Retracement Detection:** 200-bar lookback with 20% ATR tolerance - not available in free scripts
2. **Multi-Timeframe POC Confluence:** Combines 4 different POC calculations with proximity filtering
3. **Adaptive Confidence Scoring:** Dynamic risk adjustment based on signal quality with real-time tracking
4. **Institutional Order Block Analysis:** Advanced detection with directional alignment filtering
5. **Performance Verification System:** Up to 500 individual trade labels for backtesting verification
6. **Advanced Performance Analytics:** Real-time win/loss statistics for each TP level with comprehensive reporting
### Value Justification
**Why This Is Worth Using:**
- **Institutional-Grade Analysis:** Combines techniques used by professional traders
- **Proprietary Algorithms:** FVG retracement and confidence scoring not available elsewhere
- **Comprehensive Confluence:** 6 different analysis methods in one unified system
- **Professional Risk Management:** Multi-level TP system with adaptive stops
- **Real-Time Performance Tracking:** Live win/loss statistics and confidence monitoring
- **Trade Verification:** Individual trade labels for backtesting and performance analysis
- **Advanced Analytics:** Detailed performance statistics for each take-profit level
- **Time-Saving:** All analysis tools in one script vs. 6+ separate indicators
- **High Accuracy:** Multiple confluence filters reduce false signals significantly
**Technical Specifications:**
- **Pine Script Version:** 6
- **Max Bars Back:** 5000 (for historical analysis)
- **Max Labels:** 500 (for performance optimization and trade verification)
- **Memory Usage:** Optimized for real-time performance
- **Compatibility:** Works on all TradingView timeframes and instruments
- **Alert System:** Built-in alert conditions for long/short entries
- **Visual Elements:** Professional chart display with customizable colors and styles
**No External Dependencies:**
This script operates entirely within TradingView's platform with no external links, contact information, or promotional content. All analysis is performed using built-in Pine Script functions and proprietary algorithms.
Trend Candles Full ColorThe coloring over the candle sticks isn't showing up on the picture for some reason but when you click on the indicator the color coding will appear on the chart.   
Trend Candles Full Color Indicator Explanation The "Trend Candles Full Color" indicator, designed for TradingView, visually enhances candlestick charts by coloring candles based on their position relative to a simple moving average (SMA). Here's how it works and how it can benefit traders: How It Works Input : Adjust the SMA period (default is 20) to define the trend length.
Logic : The indicator compares the closing price of each candle to the SMA: Green Candle : Close is above the SMA (indicating an uptrend).
Red Candle : Close is below the SMA (indicating a downtrend).
Gray Candle : Close equals the SMA (neutral/no clear trend).
Output : Candles (body, wick, and border) are colored green, red, or gray based on the trend, overlaid directly on your price chart.
Benefits and Use Cases Trend-Following Strategies Benefit: Clearly identifies bullish (green) or bearish (red) trends, helping traders ride momentum.
Example: A swing trader using a 20-period SMA can enter long positions when candles turn green (price above SMA) and exit or short when candles turn red, confirming trend reversals.
Reversal Trading Benefit: Gray candles signal indecision near the SMA, often a precursor to reversals.
Example: A day trader might watch for gray candles after a prolonged uptrend (green candles) to anticipate a potential bearish reversal, combining with other indicators like RSI for confirmation.
Scalping Benefit: Quick visual cues for short-term trend changes on lower timeframes.
Example: A scalper on a 5-minute chart can use green candles to confirm quick bullish moves and red candles to avoid counter-trend trades, enhancing decision speed.
Position Sizing or Risk Management Benefit: Color changes highlight trend strength, aiding in adjusting trade size or stops.
Example: A trader might increase position size during strong green candle sequences (sustained uptrend) and tighten stops when gray candles appear, signaling potential trend weakness.
Tips for Use Adjust the MA Length to suit your trading style (e.g., shorter for scalping, longer for swing trading).
Combine with other indicators (e.g., support/resistance, MACD) for better accuracy.
Test on different timeframes to match your strategy.
Recommended MA Length for 1-Minute Charts Short-Term/Scalping (1-5 minute trades):10-period SMA : Very sensitive, ideal for capturing quick price movements in fast markets. May produce more noise (false signals).
20-period SMA : A balanced choice for 1-minute charts, smoothing minor fluctuations while reacting to short-term trends. A great starting point for scalpers.
Intraday Trend Trading (10-30 minute holds):50-period SMA : Captures broader intraday trends, reducing noise but lagging slightly. Suitable for larger moves within a session.
This indicator simplifies trend identification, making it a versatile tool for traders of all styles, from beginners to advanced users! 
Recommended MA Length for Swing Trading / Higher Timeframes Swing Trading (holding trades for days to weeks):50-period SMA : A popular choice for swing traders on higher timeframes (e.g., 1-hour or 4-hour charts). It smooths out short-term fluctuations while identifying medium-term trends. Ideal for capturing multi-day swings.
100-period SMA : Slightly longer, this MA is great for confirming stronger, more sustained trends. It’s useful on 4-hour or daily charts for swing traders aiming to ride larger price moves.
Longer-Term Trend Trading (holding for weeks to months):200-period SMA : A classic choice for higher timeframes like daily or weekly charts. It highlights major market trends and is widely used by swing and position traders to filter out noise and focus on long-term direction.
150-period SMA : A middle ground between the 100 and 200 SMA, suitable for daily charts when you want a balance between responsiveness and trend reliability.
Hidden Impulse═══════════════════════════════════════════════════════════════════
HIDDEN IMPULSE - Multi-Timeframe Momentum Detection System
═══════════════════════════════════════════════════════════════════
OVERVIEW
Hidden Impulse is an advanced momentum oscillator that combines the Schaff Trend Cycle (STC) and Force Index into a comprehensive multi-timeframe trading system. Unlike standard implementations of these indicators, this script introduces three distinct trading setups with specific entry conditions, multi-timeframe confirmation, and trend filtering.
═══════════════════════════════════════════════════════════════════
ORIGINALITY & KEY FEATURES
This indicator is original in the following ways:
1. DUAL-TIMEFRAME STC ANALYSIS
   Standard STC implementations work on a single timeframe. This script 
   simultaneously analyzes STC on both your trading timeframe and a higher 
   timeframe, providing trend context and filtering out low-probability signals.
2. FORCE INDEX INTEGRATION
   The script combines STC with Force Index (volume-weighted price momentum) 
   to confirm the strength behind price moves. This combination helps identify 
   when momentum shifts are backed by genuine buying/selling pressure.
3. THREE DISTINCT TRADING SETUPS
   Rather than generic overbought/oversold signals, the indicator provides 
   three specific, rule-based setups:
   - Setup A: Classic trend-following entries with multi-timeframe confirmation
   - Setup B: Divergence-based reversal entries (highest probability)
   - Setup C: Mean-reversion bounce trades at extreme levels
4. INTELLIGENT FILTERING
   All signals are filtered through:
   - 50 EMA trend direction (prevents counter-trend trades)
   - Higher timeframe STC alignment (ensures macro trend agreement)
   - Force Index confirmation (validates volume support)
═══════════════════════════════════════════════════════════════════
HOW IT WORKS - TECHNICAL EXPLANATION
SCHAFF TREND CYCLE (STC) CALCULATION:
The STC is a cyclical oscillator that combines MACD concepts with stochastic 
smoothing to create earlier and smoother trend signals.
Step 1: Calculate MACD
   - Fast MA = EMA(close, Length1) — default 23
   - Slow MA = EMA(close, Length2) — default 50
   - MACD Line = Fast MA - Slow MA
Step 2: First Stochastic Smoothing
   - Apply stochastic calculation to MACD
   - Stoch1 = 100 × (MACD - Lowest(MACD, Smoothing)) / (Highest(MACD, Smoothing) - Lowest(MACD, Smoothing))
   - Smooth result with EMA(Stoch1, Smoothing) — default 10
Step 3: Second Stochastic Smoothing
   - Apply stochastic calculation again to the smoothed stochastic
   - This creates the final STC value between 0-100
The dual stochastic smoothing makes STC more responsive than MACD while 
being smoother than traditional stochastics.
FORCE INDEX CALCULATION:
Force Index measures the power behind price movements by incorporating volume:
   Force Raw = (Close - Close ) × Volume
   Force Index = EMA(Force Raw, Period) — default 13
Interpretation:
   - Positive Force Index = Buying pressure (bulls in control)
   - Negative Force Index = Selling pressure (bears in control)
   - Force Index crossing zero = Momentum shift
   - Divergences with price = Weakening momentum (reversal signal)
TREND FILTER:
A 50-period EMA serves as the trend filter:
   - Price above EMA50 = Uptrend → Only LONG signals allowed
   - Price below EMA50 = Downtrend → Only SHORT signals allowed
This prevents counter-trend trading which accounts for most losing trades.
═══════════════════════════════════════════════════════════════════
THE THREE TRADING SETUPS - DETAILED
SETUP A: CLASSIC MOMENTUM ENTRY
Concept: Enter when STC exits oversold/overbought zones with trend confirmation
LONG CONDITIONS:
   1. Higher timeframe STC > 25 (macro trend is up)
   2. Primary timeframe STC crosses above 25 (momentum turning up)
   3. Force Index crosses above 0 OR already positive (volume confirms)
   4. Price above 50 EMA (local trend is up)
SHORT CONDITIONS:
   1. Higher timeframe STC < 75 (macro trend is down)
   2. Primary timeframe STC crosses below 75 (momentum turning down)
   3. Force Index crosses below 0 OR already negative (volume confirms)
   4. Price below 50 EMA (local trend is down)
Best for: Trending markets, continuation trades
Win rate: Moderate (60-65%)
Risk/Reward: 1:2 to 1:3
───────────────────────────────────────────────────────────────────
SETUP B: DIVERGENCE REVERSAL (HIGHEST PROBABILITY)
Concept: Identify exhaustion points where price makes new extremes but 
momentum (Force Index) fails to confirm
BULLISH DIVERGENCE:
   1. Price makes a lower low (LL) over 10 bars
   2. Force Index makes a higher low (HL) — refuses to follow price down
   3. STC is below 25 (oversold condition)
   
   Trigger: STC starts rising AND Force Index crosses above zero
BEARISH DIVERGENCE:
   1. Price makes a higher high (HH) over 10 bars
   2. Force Index makes a lower high (LH) — refuses to follow price up
   3. STC is above 75 (overbought condition)
   
   Trigger: STC starts falling AND Force Index crosses below zero
Why this works: Divergences signal that the current trend is losing steam. 
When volume (Force Index) doesn't confirm new price extremes, a reversal 
is likely.
Best for: Reversal trading, range-bound markets
Win rate: High (70-75%)
Risk/Reward: 1:3 to 1:5
───────────────────────────────────────────────────────────────────
SETUP C: QUICK BOUNCE AT EXTREMES
Concept: Catch rapid mean-reversion moves when price touches EMA50 in 
extreme STC zones
LONG CONDITIONS:
   1. Price touches 50 EMA from above (pullback in uptrend)
   2. STC < 15 (extreme oversold)
   3. Force Index > 0 (buyers stepping in)
SHORT CONDITIONS:
   1. Price touches 50 EMA from below (pullback in downtrend)
   2. STC > 85 (extreme overbought)
   3. Force Index < 0 (sellers stepping in)
Best for: Scalping, quick mean-reversion trades
Win rate: Moderate (55-60%)
Risk/Reward: 1:1 to 1:2
Note: Use tighter stops and quick profit-taking
═══════════════════════════════════════════════════════════════════
HOW TO USE THE INDICATOR
STEP 1: CONFIGURE TIMEFRAMES
Primary Timeframe (STC - Primary Timeframe):
   - Leave empty to use your current chart timeframe
   - This is where you'll take trades
Higher Timeframe (STC - Higher Timeframe):
   - Default: 30 minutes
   - Recommended ratios:
     * 5min chart → 30min higher TF
     * 15min chart → 1H higher TF
     * 1H chart → 4H higher TF
     * Daily chart → Weekly higher TF
───────────────────────────────────────────────────────────────────
STEP 2: ADJUST STC PARAMETERS FOR YOUR MARKET
Default (23/50/10) works well for stocks and forex, but adjust for:
CRYPTO (volatile):
   - Length 1: 15
   - Length 2: 35
   - Smoothing: 8
   (Faster response for rapid price movements)
STOCKS (standard):
   - Length 1: 23
   - Length 2: 50
   - Smoothing: 10
   (Balanced settings)
FOREX MAJORS (slower):
   - Length 1: 30
   - Length 2: 60
   - Smoothing: 12
   (Filters out noise in 24/7 markets)
───────────────────────────────────────────────────────────────────
STEP 3: ENABLE YOUR PREFERRED SETUPS
Toggle setups based on your trading style:
Conservative Trader:
   ✓ Setup B (Divergence) — highest win rate
   ✗ Setup A (Classic) — only in strong trends
   ✗ Setup C (Bounce) — too aggressive
Trend Trader:
   ✓ Setup A (Classic) — primary signals
   ✓ Setup B (Divergence) — for entries on pullbacks
   ✗ Setup C (Bounce) — not suitable for trending
Scalper:
   ✓ Setup C (Bounce) — quick in-and-out
   ✓ Setup B (Divergence) — high probability scalps
   ✗ Setup A (Classic) — too slow
───────────────────────────────────────────────────────────────────
STEP 4: READ THE SIGNALS
ON THE CHART:
   Labels appear when conditions are met:
   
   Green labels:
   - "LONG A" — Setup A long entry
   - "LONG B DIV" — Setup B divergence long (best signal)
   - "LONG C" — Setup C bounce long
   
   Red labels:
   - "SHORT A" — Setup A short entry
   - "SHORT B DIV" — Setup B divergence short (best signal)
   - "SHORT C" — Setup C bounce short
IN THE INDICATOR PANEL (bottom):
   - Blue line = Primary timeframe STC
   - Orange dots = Higher timeframe STC (optional)
   - Green/Red bars = Force Index histogram
   - Dashed lines at 25/75 = Entry/Exit zones
   - Background shading = Oversold (green) / Overbought (red)
INFO TABLE (top-right corner):
   Shows real-time status:
   - STC values for both timeframes
   - Force Index direction
   - Price position vs EMA
   - Current trend direction
   - Active signal type
═══════════════════════════════════════════════════════════════════
TRADING STRATEGY & RISK MANAGEMENT
ENTRY RULES:
Priority ranking (best to worst):
   1st: Setup B (Divergence) — wait for these
   2nd: Setup A (Classic) — in confirmed trends only
   3rd: Setup C (Bounce) — scalping only
Confirmation checklist before entry:
   ☑ Signal label appears on chart
   ☑ TREND in info table matches signal direction
   ☑ Higher timeframe STC aligned (check orange dots or table)
   ☑ Force Index confirming (check histogram color)
───────────────────────────────────────────────────────────────────
STOP LOSS PLACEMENT:
Setup A (Classic):
   - LONG: Below recent swing low
   - SHORT: Above recent swing high
   - Typical: 1-2 ATR distance
Setup B (Divergence):
   - LONG: Below the divergence low
   - SHORT: Above the divergence high
   - Typical: 0.5-1.5 ATR distance
Setup C (Bounce):
   - LONG: 5-10 pips below EMA50
   - SHORT: 5-10 pips above EMA50
   - Typical: 0.3-0.8 ATR distance
───────────────────────────────────────────────────────────────────
TAKE PROFIT TARGETS:
Conservative approach:
   - Exit when STC reaches opposite level
   - LONG: Exit when STC > 75
   - SHORT: Exit when STC < 25
Aggressive approach:
   - Hold until opposite signal appears
   - Trail stop as STC moves in your favor
Partial profits:
   - Take 50% at 1:2 risk/reward
   - Let remaining 50% run to target
───────────────────────────────────────────────────────────────────
WHAT TO AVOID:
❌ Trading Setup A in sideways/choppy markets
   → Wait for clear trend or use Setup B only
❌ Ignoring higher timeframe STC
   → Always check orange dots align with your direction
❌ Taking signals against the major trend
   → If weekly trend is down, be cautious with longs
❌ Overtrading Setup C
   → Maximum 2-3 bounce trades per session
❌ Trading during low volume periods
   → Force Index becomes unreliable
═══════════════════════════════════════════════════════════════════
ALERTS CONFIGURATION
The indicator includes 8 alert types:
Individual setup alerts:
   - "Setup A - LONG" / "Setup A - SHORT"
   - "Setup B - DIV LONG" / "Setup B - DIV SHORT" ⭐ recommended
   - "Setup C - BOUNCE LONG" / "Setup C - BOUNCE SHORT"
Combined alerts:
   - "ANY LONG" — fires on any long signal
   - "ANY SHORT" — fires on any short signal
Recommended alert setup:
   - Create "Setup B - DIV LONG" and "Setup B - DIV SHORT" alerts
   - These are the highest probability signals
   - Set "Once Per Bar Close" to avoid false alerts
═══════════════════════════════════════════════════════════════════
VISUALIZATION SETTINGS
Show Labels on Chart:
   Toggle on/off the signal labels (green/red)
   Disable for cleaner chart once you're familiar with the indicator
Show Higher TF STC:
   Toggle the orange dots showing higher timeframe STC
   Useful for visual confirmation of multi-timeframe alignment
Info Panel:
   Cannot be disabled — always shows current status
   Positioned top-right to avoid chart interference
═══════════════════════════════════════════════════════════════════
EXAMPLE TRADE WALKTHROUGH
SETUP B DIVERGENCE LONG EXAMPLE:
1. Market Context:
   - Price in downtrend, below 50 EMA
   - Multiple lower lows forming
   - STC below 25 (oversold)
2. Divergence Formation:
   - Price makes new low at $45.20
   - Force Index refuses to make new low (higher low forms)
   - This indicates selling pressure weakening
3. Signal Trigger:
   - STC starts turning up
   - Force Index crosses above zero
   - Label appears: "LONG B DIV"
4. Trade Execution:
   - Entry: $45.50 (current price at signal)
   - Stop Loss: $44.80 (below divergence low)
   - Target 1: $47.90 (STC reaches 75) — risk/reward 1:3.4
   - Target 2: Opposite signal or trail stop
5. Trade Management:
   - Price rallies to $47.20
   - STC reaches 68 (approaching target zone)
   - Take 50% profit, move stop to breakeven
   - Exit remaining at $48.10 when STC crosses 75
Result: 3.7R gain
═══════════════════════════════════════════════════════════════════
ADVANCED TIPS
1. MULTI-TIMEFRAME CONFLUENCE
   For highest probability trades, wait for:
   - Primary TF signal
   - Higher TF STC aligned (>25 for longs, <75 for shorts)
   - Even higher TF trend in same direction (manual check)
2. VOLUME CONFIRMATION
   Watch the Force Index histogram:
   - Increasing bar size = Strengthening momentum
   - Decreasing bar size = Weakening momentum
   - Use this to gauge signal strength
3. AVOID THESE MARKET CONDITIONS
   - Major news events (Force Index becomes erratic)
   - Market open first 30 minutes (volatility spikes)
   - Low liquidity instruments (Force Index unreliable)
   - Extreme trending days (wait for pullbacks)
4. COMBINE WITH SUPPORT/RESISTANCE
   Best signals occur near:
   - Key horizontal levels
   - Fibonacci retracements
   - Previous day's high/low
   - Psychological round numbers
5. SESSION AWARENESS
   - Asia session: Use lower timeframes, Setup C works well
   - London session: Setup A and B both effective
   - New York session: All setups work, highest volume
═══════════════════════════════════════════════════════════════════
INDICATOR WINDOWS LAYOUT
MAIN CHART:
   - Price action
   - 50 EMA (green/red)
   - Signal labels
   - Info panel
INDICATOR WINDOW:
   - STC oscillator (blue line, 0-100 scale)
   - Higher TF STC (orange dots, optional)
   - Force Index histogram (green/red bars)
   - Reference levels (25, 50, 75)
   - Background zones (green oversold, red overbought)
═══════════════════════════════════════════════════════════════════
PERFORMANCE OPTIMIZATION
For best results:
Backtesting:
   - Test on your specific instrument and timeframe
   - Adjust STC parameters if win rate < 55%
   - Record which setup works best for your market
Position Sizing:
   - Risk 1-2% per trade
   - Setup B can use 2% risk (higher win rate)
   - Setup C should use 1% risk (lower win rate)
Trade Frequency:
   - Setup B: 2-5 signals per week (be patient)
   - Setup A: 5-10 signals per week
   - Setup C: 10+ signals per week (scalping)
═══════════════════════════════════════════════════════════════════
CREDITS & REFERENCES
This indicator builds upon established technical analysis concepts:
Schaff Trend Cycle:
   - Developed by Doug Schaff (1996)
   - Original concept published in Technical Analysis of Stocks & Commodities
   - Implementation based on standard STC formula
Force Index:
   - Developed by Dr. Alexander Elder
   - Described in "Trading for a Living" (1993)
   - Classic volume-momentum indicator
The multi-timeframe integration, three-setup system, and specific 
entry conditions are original contributions of this indicator.
═══════════════════════════════════════════════════════════════════
DISCLAIMER
This indicator is a technical analysis tool and does not guarantee profits. 
Past performance is not indicative of future results. Always:
   - Use proper risk management
   - Test on demo account first
   - Combine with fundamental analysis
   - Never risk more than you can afford to lose
═══════════════════════════════════════════════════════════════════
SUPPORT & QUESTIONS
If you find this indicator helpful, please:
   - Leave a like and comment
   - Share your feedback and results
   - Report any bugs or issues
For questions about usage or optimization for specific markets, 
feel free to comment below.
═════════════════════════════════════════════════════════════
Dynamic Market Structure (MTF) - Dow TheoryDynamic Market Structure (MTF) 
 OVERVIEW 
This advanced indicator provides a comprehensive and fully customizable solution for analyzing market structure based on classic Dow Theory principles. It automates the identification of key structural points, including Higher Highs (HH), Higher Lows (HL), Lower Lows (LL), and Lower Highs (LH).
Going beyond simple pivot detection, this tool visualizes the flow of the trend by plotting dynamic Breaks of Structure (BOS) and potential reversals with Changes of Character (CHoCH). It is designed to be a flexible and powerful tool for traders who use price action and trend analysis as a core part of their strategy.
CORE CONCEPTS
The indicator is built on the foundational principles of Dow Theory:
 
 Uptrend: A series of Higher Highs and Higher Lows.
 Downtrend: A series of Lower Lows and Lower Highs.
 Break of Structure (BOS): Occurs when price action continues the current trend by creating a new HH in an uptrend or a new LL in a downtrend.
 Change of Character (CHoCH): Occurs when the established trend sequence is broken, signaling a potential reversal. For example, when a Lower Low forms after a series of Higher Highs.
 
CALCULATION METHODOLOGY
This section explains the indicator's underlying logic:
Pivot Detection: The indicator's core logic is based on TradingView's built-in  ta.pivothigh()  and  ta.pivotlow()  functions. The sensitivity of this detection is fully controlled by the user via the Pivot Lookback Left and Pivot Lookback Right settings.
Structure Calculation (BOS/CHoCH): The script identifies market structure by analyzing the sequence of these confirmed pivots.
 
 A bullish BOS is plotted when a new  ta.pivothigh  is confirmed at a price higher than the previous confirmed ta.pivothigh.
 A bearish CHoCH is plotted when a new  ta.pivotlow  is confirmed at a price lower than the previous confirmed  ta.pivotlow , breaking the established sequence of higher lows.
 The logic is mirrored for bearish BOS and bullish CHoCH.
 
Invalidation Levels: This feature identifies the last confirmed pivot before a structure break (e.g., the last  ta.pivotlow  before a bullish BOS) and plots a dotted line from it to the breakout bar. This level is considered the structural invalidation point for that move.
MTF Confirmation: This unique feature provides confluence by analyzing a second, lower timeframe. When a pivot (e.g., a Higher Low) is confirmed on the main chart, the script requests pivot data from the user-selected lower timeframe. If a corresponding trend reversal is detected on that lower timeframe (e.g., a break of its own minor downtrend), the pivot is labeled "Firm" (FHL); otherwise, it is labeled "Soft" (SHL).
KEY FEATURES
This indicator is packed with advanced features designed to provide a deeper level of market insight:
 
 Dynamic Structure Lines: BOS and CHoCH levels are plotted with clean, dashed lines that dynamically start at the old pivot and terminate precisely at the breakout bar, keeping the chart clean and precise.
 Invalidation Levels: For every structure break, the indicator can plot a dotted "Invalidation" line (INV). This marks the critical support or resistance pivot that, if broken, would negate the previous move, providing a clear reference for risk management.
 Multi-Timeframe (MTF) Confirmation: Add a layer of confluence to your analysis by confirming pivots on a lower timeframe. The indicator can label Higher Lows and Lower Highs as either "Firm" (FHL/FLH) if confirmed by a reversal on a lower timeframe, or "Soft" (SHL/SLH) if not.
 Flexible Pivot Detection: Fully adjustable  Pivot Lookback  settings for the left and right sides allow you to tune the indicator's sensitivity to match any timeframe or trading style, from long-term investing to short-term scalping.
 Full Customization: Take complete control of the indicator's appearance. A dedicated style menu allows you to customize the colors for all bullish, bearish, and reversal elements, including the transparency of the trend-based candle coloring.
 
HOW TO USE
 
 Trend Identification: Use the sequence of HH/HL and LL/LH, along with the trend-colored candles, to quickly assess the current market direction on any timeframe.
 Entry Signals: A confirmed BOS can signal a potential entry in the direction of the trend. A CHoCH can signal a potential reversal, offering an opportunity to enter a new trend early.
 Risk Management: Use the automatically plotted "Invalidation" (INV) lines as a logical reference point for placing stop losses. A break of this level indicates that the structure you were trading has failed.
 Confluence: Use the "Firm" pivot signals from the MTF analysis to identify high-probability swing points that are supported by price action on multiple timeframes.
 
SETTINGS BREAKDOWN
 
 Pivot Lookback Left/Right: Controls the sensitivity of pivot detection. Higher numbers find more significant (but fewer) pivots.
 MTF Confirmation: Enable/disable the "Firm" vs. "Soft" pivot analysis and select your preferred lower timeframe for confirmation.
 Style Settings: Customize all colors and the transparency of the candle coloring to match your chart's theme.
 Show Invalidation Levels: Toggle the visibility of the dotted invalidation lines.
 
This indicator is a powerful tool for visualizing and trading with the trend. Experiment with the settings to find a configuration that best fits your personal trading strategy.
Historical Matrix Analyzer [PhenLabs]📊Historical Matrix Analyzer  
 Version:  PineScriptv6
 📌Description 
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
 🚀Points of Innovation 
 
 Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
 Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
 Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
 Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
 Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
 Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
 
 🔧Core Components 
 
 RSI State Classification:  Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
 Multi-Indicator Condition Tracking:  Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
 Historical Data Storage Arrays:  Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
 Forward Performance Calculator:  Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
 Bayesian Smoothing Engine:  Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
 Dynamic Color Mapping System:  Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
 
 🔥Key Features 
 
 56-Cell Probability Matrix:  Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
 Current State Info Panel:  Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
 Customizable Lookback Period:  Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
 Configurable Forward Performance Window:  Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
 Visual Heat Mapping:  Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
 Intelligent Data Filtering:  Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
 Flexible Layout Options:  Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
 Tooltip Details:  Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
 
 🎨Visualization 
 
 Statistics Matrix Table:  A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
 Active Cell Indicator:  The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
 Signal Strength Visualization:  Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
 Histogram Plot:  Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
 Color Intensity Scaling:  Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
 Confidence Level Display:  Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
 
 📖Usage Guidelines 
 RSI Period 
 
 Default: 14
 Range: 1 to unlimited
 Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
 
 MACD Fast Length 
 
 Default: 12
 Range: 1 to unlimited
 Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
 
 MACD Slow Length 
 
 Default: 26
 Range: 1 to unlimited
 Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
 
 MACD Signal Length 
 
 Default: 9
 Range: 1 to unlimited
 Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
 
 Volume MA Period 
 
 Default: 20
 Range: 1 to unlimited
 Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
 
 Statistics Lookback Period 
 
 Default: 200
 Range: 50 to 500
 Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
 
 Forward Performance Bars 
 
 Default: 5
 Range: 1 to 20
 Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
 
 Color Intensity Sensitivity 
 
 Default: 2.0
 Range: 0.5 to 5.0, step 0.5
 Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
 
 Minimum Occurrences for Coloring 
 
 Default: 3
 Range: 1 to 10
 Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
 
 Table Position 
 
 Default: top_right
 Options: top_left, top_right, bottom_left, bottom_right
 Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
 
 Show Current State Panel 
 
 Default: true
 Options: true, false
 Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
 
 Info Panel Position 
 
 Default: bottom_left
 Options: top_left, top_right, bottom_left, bottom_right
 Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
 
 Win Rate Smoothing Strength 
 
 Default: 5
 Range: 1 to 20
 Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
 
 ✅Best Use Cases 
 
 Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
 Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
 Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
 Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
 Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
 Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
 
 ⚠️Limitations 
 
 Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
 Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
 Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
 Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
 
 💡What Makes This Unique 
 
 Multi-Dimensional State Space:  Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
 Bayesian Statistical Rigor:  Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
 Real-Time Contextual Feedback:  The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
 Transparent Occurrence Counts:  Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
 Fully Customizable Analysis Window:  Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
 
 🔬How It Works 
 1. State Classification and Encoding 
 
 Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
 Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
 These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
 The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
 
 2. Historical Data Accumulation 
 
 As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
 When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
 This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
 
 3. Forward Return Calculation and Statistics Update 
 
 On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
 For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
 This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
 Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
 The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
 
 💡Note: 
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights.
DAMMU Swing Trading PRODammu Scalping Pro – Short Notes
1️⃣ Purpose:
Scalping and swing trading tool for 15-min and 1-min charts.
Designed for trend continuation, pullbacks, and reversals.
Works well with Heikin Ashi candles (optional).
2️⃣ Core Components:
EMAs:
Fast: EMA5-12
Medium: EMA12-36 Ribbon
Long: EMA75/89 (1-min), EMA180/200 (15-min), EMA540/633
Price Action Channel (PAC): EMA-based High, Low, Close channel.
Fractals: Regular & filtered (BW) fractals for swing recognition.
Higher Highs / Lower Highs / Higher Lows / Lower Lows (HH, LH, HL, LL).
Pivot Points: Optional display with labels.
3️⃣ Bar Coloring:
Blue: Close above PAC
Red: Close below PAC
Gray: Close inside PAC
4️⃣ Alerts:
Swing Buy/Sell arrows based on PAC breakout and EMA200 filter.
Optional “Big Arrows” mode for visibility.
Alert messages: "SWING_UP" and "SWING_DN"
5️⃣ Workflow / Usage Tips:
Set chart to 15-min (for trend) + 1-min (for entry).
Optionally enable Heikin Ashi candles.
Trade long only above EMA200, short only below EMA200.
Watch for pullbacks into EMA channels or ribbons.
Confirm trend resumption via PAC breakout & bar color change.
Use fractals and pivot points to draw trendlines and locate support/resistance.
6️⃣ Optional Filters:
Filter PAC signals with 200 EMA.
Filter fractals for “Pristine/Ideal” patterns (BW filter).
7️⃣ Visuals:
EMA ribbons, PAC fill, HH/LL squares, fractal triangles.
Pivot labels & candle numbering for patterns.
8️⃣ Notes:
No extra indicators needed except optionally SweetSpot Gold2 for major S/R levels.
Suitable for scalping pullbacks with trend confirmation.
If you want, I can make an even shorter “one-screen cheat sheet” with colors, alerts, and EMAs, perfect for real-time chart reference.
Do you want me to do that?
DAMMU Swing Trading PRODammu Scalping Pro – Short Notes
1️⃣ Purpose:
Scalping and swing trading tool for 15-min and 1-min charts.
Designed for trend continuation, pullbacks, and reversals.
Works well with Heikin Ashi candles (optional).
2️⃣ Core Components:
EMAs:
Fast: EMA5-12
Medium: EMA12-36 Ribbon
Long: EMA75/89 (1-min), EMA180/200 (15-min), EMA540/633
Price Action Channel (PAC): EMA-based High, Low, Close channel.
Fractals: Regular & filtered (BW) fractals for swing recognition.
Higher Highs / Lower Highs / Higher Lows / Lower Lows (HH, LH, HL, LL).
Pivot Points: Optional display with labels.
3️⃣ Bar Coloring:
Blue: Close above PAC
Red: Close below PAC
Gray: Close inside PAC
4️⃣ Alerts:
Swing Buy/Sell arrows based on PAC breakout and EMA200 filter.
Optional “Big Arrows” mode for visibility.
Alert messages: "SWING_UP" and "SWING_DN"
5️⃣ Workflow / Usage Tips:
Set chart to 15-min (for trend) + 1-min (for entry).
Optionally enable Heikin Ashi candles.
Trade long only above EMA200, short only below EMA200.
Watch for pullbacks into EMA channels or ribbons.
Confirm trend resumption via PAC breakout & bar color change.
Use fractals and pivot points to draw trendlines and locate support/resistance.
6️⃣ Optional Filters:
Filter PAC signals with 200 EMA.
Filter fractals for “Pristine/Ideal” patterns (BW filter).
7️⃣ Visuals:
EMA ribbons, PAC fill, HH/LL squares, fractal triangles.
Pivot labels & candle numbering for patterns.
8️⃣ Notes:
No extra indicators needed except optionally SweetSpot Gold2 for major S/R levels.
Suitable for scalping pullbacks with trend confirmation.
If you want, I can make an even shorter “one-screen cheat sheet” with colors, alerts, and EMAs, perfect for real-time charT
MACD Pro - Multi-Filter Smart Divergence System# MACD Pro - Multi-Filter Smart Divergence System
## Professional MACD with Advanced Filtering & Automatic Divergence Detection
Transform the classic MACD indicator with professional-grade filters, automated divergence detection, and pre-optimized profiles for different markets.
---
## KEY FEATURES
### Smart Signal Filtering
- **Zero-Line Territory Filter** - Eliminates weak crossovers
- **3-Period Confirmation** - Reduces false signals
- **Minimum Distance Threshold** - Filters out noise
- **Multi-Indicator Confirmation** - RSI + Volume validation
### Automatic Divergence Detection
- **Visual Divergence Lines** - Connects price and MACD pivots automatically
- **Bullish/Bearish Recognition** - Real-time identification
- **Customizable Lookback** - Adjust sensitivity
- **Clean Display** - Managed line limits
### Pre-Optimized Market Profiles
- **S&P 500** (2/60/2) - Tested +3.63% annual
- **Gold** (14/48/3) - Optimized for volatility
- **Forex 30m** (24/52/9) - 24/7 market adapted
- **Scalping 1m** (5/13/6) - Quick trades
- **Linda Raschke** (3/10/16) - Classic scalping
- **Swing Trading** (8/24/9) - Higher timeframes
### Advanced Technical Features
- **ATR Normalization** - Volatility adaptation
- **Predictive Forecast** - Linear regression projection
- **Multi-Timeframe View** - Higher TF overlay
- **Volume Analysis** - Spike confirmation
- **Professional Dashboard** - Real-time metrics
---
## HOW TO USE
**Quick Start:**
1. Enable "Use Optimized Profile"
2. Select your market type
3. Watch for signal arrows and divergence lines
4. Confirm with dashboard metrics
**Signal Types:**
- 🔺 Green Triangle = Bullish crossover (filtered)
- 🔻 Red Triangle = Bearish crossover (filtered)
- ⚪ Small Circle = Conservative zero-line cross
- 🟢 Green Line = Bullish divergence
- 🔴 Red Line = Bearish divergence
---
## CUSTOMIZATION
**Filters:** Toggle each filter independently for your risk tolerance
**Divergence:** Adjust lookback period, line width, and maximum displayed lines
**Confirmation:** Customize RSI levels and volume spike thresholds
**Display:** Choose histogram, forecast, and multi-timeframe options
---
## ALERT CONDITIONS
- MACD Long Signal
- MACD Short Signal
- Bullish Divergence
- Bearish Divergence
---
## IMPORTANT NOTES
**Repainting:** Divergence detection uses historical pivots and may redraw. Crossover signals are non-repainting.
**Disclaimer:** Pre-optimized profiles based on historical data. Past performance does not guarantee future results. This indicator is for educational purposes only, not financial advice.
---
## BEST PRACTICES
**Timeframes:**
- 1-5m → Scalping profile
- 15-30m → Forex profile
- 1-4h → Swing profile
- Daily → S&P 500/Gold profiles
**Market Conditions:**
- Trending → Focus on momentum
- Ranging → Enable all filters, watch divergences
- Volatile → Use ATR normalization
**Combine With:** Support/resistance levels, trendlines, moving averages, and price action analysis.
---
## WHY MACD PRO?
| Feature | Standard MACD | MACD Pro |
|---------|--------------|----------|
| Signal Filters | ❌ | ✅ 5 Advanced |
| Divergence | ❌ Manual | ✅ Automatic |
| Market Profiles | ❌ | ✅ 7 Optimized |
| Volume Filter | ❌ | ✅ Built-in |
| Multi-Timeframe | ❌ | ✅ Yes |
| ATR Adaptation | ❌ | ✅ Yes |
---
**If you find this indicator useful, please boost 🚀**
*Protected source code. Compatible with all TradingView plans.*
nadia
Gold ramon strategy based on 50 candles and atr of 12
You enter the maximum of 50 candles once the most bearish starts to rise, we expect 10 candles, if you don't go up in 10 candles, you don't enter, if you go up before 10 candles, you enter.
When is TP? Enough with 5 candles
The temporality is 1 hour. It can be adjusted to 1 minute temporality for scalping.
It is never lost, because it always exceeds the previous maximums.
Quantum Flux Universal Strategy Summary in one paragraph 
Quantum Flux Universal is a regime switching strategy for stocks, ETFs, index futures, major FX pairs, and liquid crypto on intraday and swing timeframes. It helps you act only when the normalized core signal and its guide agree on direction. It is original because the engine fuses three adaptive drivers into the smoothing gains itself. Directional intensity is measured with binary entropy, path efficiency shapes trend quality, and a volatility squash preserves contrast. Add it to a clean chart, watch the polarity lane and background, and trade from positive or negative alignment. For conservative workflows use on bar close in the alert settings when you add alerts in a later version.
 Scope and intent 
• Markets. Large cap equities and ETFs. Index futures. Major FX pairs. Liquid crypto
• Timeframes. One minute to daily
• Default demo used in the publication. QQQ on one hour
• Purpose. Provide a robust and portable way to detect when momentum and confirmation align, while dampening chop and preserving turns
• Limits. This is a strategy. Orders are simulated on standard candles only
 
Originality and usefulness 
• Unique concept or fusion. The novelty sits in the gain map. Instead of gating separate indicators, the model mixes three drivers into the adaptive gains that power two one pole filters. Directional entropy measures how one sided recent movement has been. Kaufman style path efficiency scores how direct the path has been. A volatility squash stabilizes step size. The drivers are blended into the gains with visible inputs for strength, windows, and clamps.
• What failure mode it addresses. False starts in chop and whipsaw after fast spikes. Efficiency and the squash reduce over reaction in noise.
• Testability. Every component has an input. You can lengthen or shorten each window and change the normalization mode. The polarity plot and background provide a direct readout of state.
• Portable yardstick. The core is normalized with three options. Z score, percent rank mapped to a symmetric range, and MAD based Z score. Clamp bounds define the effective unit so context transfers across symbols.
 Method overview in plain language 
The strategy computes two smoothed tracks from the chart price source. The fast track and the slow track use gains that are not fixed. Each gain is modulated by three drivers. A driver for directional intensity, a driver for path efficiency, and a driver for volatility. The difference between the fast and the slow tracks forms the raw flux. A small phase assist reduces lag by subtracting a portion of the delayed value. The flux is then normalized. A guide line is an EMA of a small lead on the flux. When the flux and its guide are both above zero, the polarity is positive. When both are below zero, the polarity is negative. Polarity changes create the trade direction.
Base measures
• Return basis. The step is the change in the chosen price source. Its absolute value feeds the volatility estimate. Mean absolute step over the window gives a stable scale.
• Efficiency basis. The ratio of net move to the sum of absolute step over the window gives a value between zero and one. High values mean trend quality. Low values mean chop.
• Intensity basis. The fraction of up moves over the window plugs into binary entropy. Intensity is one minus entropy, which maps to zero in uncertainty and one in very one sided moves.
 Components
 • Directional Intensity. Measures how one sided recent bars have been. Smoothed with RMA. More intensity increases the gain and makes the fast and slow tracks react sooner.
• Path Efficiency. Measures the straightness of the price path. A gamma input shapes the curve so you can make trend quality count more or less. Higher efficiency lifts the gain in clean trends.
• Volatility Squash. Normalizes the absolute step with Z score then pushes it through an arctangent squash. This caps the effect of spikes so they do not dominate the response.
• Normalizer. Three modes. Z score for familiar units, percent rank for a robust monotone map to a symmetric range, and MAD based Z for outlier resistance.
• Guide Line. EMA of the flux with a small lead term that counteracts lag without heavy overshoot.
 Fusion rule
 • Weighted sum of the three drivers with fixed weights visible in the code comments. Intensity has fifty percent weight. Efficiency thirty percent. Volatility twenty percent.
• The blend power input scales the driver mix. Zero means fixed spans. One means full driver control.
• Minimum and maximum gain clamps bound the adaptive gain. This protects stability in quiet or violent regimes.
 Signal rule 
• Long suggestion appears when flux and guide are both above zero. That sets polarity to plus one.
• Short suggestion appears when flux and guide are both below zero. That sets polarity to minus one.
• When polarity flips from plus to minus, the strategy closes any long and enters a short.
• When flux crosses above the guide, the strategy closes any short.
 What you will see on the chart 
• White polarity plot around the zero line
• A dotted reference line at zero named Zen
• Green background tint for positive polarity and red background tint for negative polarity
• Strategy long and short markers placed by the TradingView engine at entry and at close conditions
• No table in this version to keep the visual clean and portable
 Inputs with guidance 
 Setup 
• Price source. Default ohlc4. Stable for noisy symbols.
• Fast span. Typical range 6 to 24. Raising it slows the fast track and can reduce churn. Lowering it makes entries more reactive.
• Slow span. Typical range 20 to 60. Raising it lengthens the baseline horizon. Lowering it brings the slow track closer to price.
 
Logic 
• Guide span. Typical range 4 to 12. A small guide smooths without eating turns.
• Blend power. Typical range 0.25 to 0.85. Raising it lets the drivers modulate gains more. Lowering it pushes behavior toward fixed EMA style smoothing.
• Vol window. Typical range 20 to 80. Larger values calm the volatility driver. Smaller values adapt faster in intraday work.
• Efficiency window. Typical range 10 to 60. Larger values focus on smoother trends. Smaller values react faster but accept more noise.
• Efficiency gamma. Typical range 0.8 to 2.0. Above one increases contrast between clean trends and chop. Below one flattens the curve.
• Min alpha multiplier. Typical range 0.30 to 0.80. Lower values increase smoothing when the mix is weak.
• Max alpha multiplier. Typical range 1.2 to 3.0. Higher values shorten smoothing when the mix is strong.
• Normalization window. Typical range 100 to 300. Larger values reduce drift in the baseline.
• Normalization mode. Z score, percent rank, or MAD Z. Use MAD Z for outlier heavy symbols.
• Clamp level. Typical range 2.0 to 4.0. Lower clamps reduce the influence of extreme runs.
 Filters 
• Efficiency filter is implicit in the gain map. Raising efficiency gamma and the efficiency window increases the preference for clean trends.
• Micro versus macro relation is handled by the fast and slow spans. Increase separation for swing, reduce for scalping.
• Location filter is not included in v1.0. If you need distance gates from a reference such as VWAP or a moving mean, add them before publication of a new version.
 Alerts 
• This version does not include alertcondition lines to keep the core minimal. If you prefer alerts, add names Long Polarity Up, Short Polarity Down, Exit Short on Flux Cross Up in a later version and select on bar close for conservative workflows.
Strategy has been currently adapted for the QQQ asset with 30/60min timeframe.
 For other assets may require new optimization 
 
Properties visible in this publication
• Initial capital 25000
• Base currency Default
• Default order size method percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
 Honest limitations and failure modes 
• Past results do not guarantee future outcomes
• Economic releases, circuit breakers, and thin books can break the assumptions behind intensity and efficiency
• Gap heavy symbols may benefit from the MAD Z normalization
• Very quiet regimes can reduce signal contrast. Use longer windows or higher guide span to stabilize context
• Session time is the exchange time of the chart
• If both stop and target can be hit in one bar, tie handling would matter. This strategy has no fixed stops or targets. It uses polarity flips for exits. If you add stops later, declare the preference
 Open source reuse and credits 
• None beyond public domain building blocks and Pine built ins such as EMA, SMA, standard deviation, RMA, and percent rank
• Method and fusion are original in construction and disclosure
 Legal 
Education and research only. Not investment advice. You are responsible for your decisions. Test on historical data and in simulation before any live use. Use realistic costs.
 Strategy add on block 
Strategy notice
Orders are simulated by the TradingView engine on standard candles. No request.security() calls are used.
 Entries and exits 
• Entry logic. Enter long when both the normalized flux and its guide line are above zero. Enter short when both are below zero
• Exit logic. When polarity flips from plus to minus, close any long and open a short. When the flux crosses above the guide line, close any short
• Risk model. No initial stop or target in v1.0. The model is a regime flipper. You can add a stop or trail in later versions if needed
• Tie handling. Not applicable in this version because there are no fixed stops or targets
 Position sizing 
• Percent of equity in the Properties panel. Five percent is the default for examples. Risk per trade should not exceed five to ten percent of equity. One to two percent is a common choice
 Properties used on the published chart 
• Initial capital 25000
• Base currency Default
• Default order size percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
Dataset and sample size
• Test window Jan 2, 2014 to Oct 16, 2025 on QQQ one hour
• Trade count in sample 324 on the example chart
Release notes template for future updates
Version 1.1.
• Add alertcondition lines for long, short, and exit short
• Add optional table with component readouts
• Add optional stop model with a distance unit expressed as ATR or a percent of price
Notes. Backward compatibility Yes. Inputs migrated Yes.
Copter 2.0💡 The indicator is designed for trading on any timeframe and includes a comprehensive system for determining entry and exit points based on technical analysis, price and volume.
📊 In the new version of Copter 2.0, the take profit and stop loss functions have been added
Let's analyze its key components:
✔️ Trend levels and extremes:
- The indicator determines local highs and lows for a certain period.
- the breakdown of these levels serves as a signal to open positions.
- the High-Low price dynamics analysis method is used to find key entry points.
✔️ Volumes:
-The indicator uses a configurable volume threshold to filter out candles with low volume and display only those with significant volume.
- the algorithm analyzes market data and sets an entry signal (opening a trade) and exit (profit taking/closing a position)
📍 Therefore, whether you are a beginner or an experienced trader, the indicator can help you stay ahead of the game and make more informed trading decisions.
📍 As a result, the trader can be sure that the signal is based on data analysis.
A long or short position can be stopped with either a profit or a small loss without prejudice to the potential profit.
✔️ Signal filtering:
- volume and volatile indicators are used to confirm the trend
- if a volume or volatility filter does not confirm the breakdown, the input signal is ignored
- analysis of moving averages of volumes and ATR is used
✔️ The use of the RSI in overbought and oversold analysis:
- the RSI indicator analyzes the strength of the current trend
- if the RSI exceeds 70, exit from a long position is possible
- if the RSI falls below 30, exit from a short position is possible
✔️ The use of EMA 20 and EMA 200
is additional moving average data that determines the current trend and the trend on higher timeframes.
- the main idea is that when they cross, we can see a change in trend movement and determine the general mood at the moment, based on which signals appear to open/close a deal.
- also, the indicator analyzes the past movement, thus determining the future direction
- based on the opening and closing of the past days, weeks, months.
✔️ Stop loss and risk management
- when entering a trade, a dynamic stop loss is set based on the percentage price change
- exit the position is carried out when a stop loss or a signal from the RSI is reached.
- it helps to minimize losses and protect profits
The market is unstable, and it is impossible to know what awaits it in the future.
The only way to manage risk is to limit the loss by setting a stop loss at 1% - 2% of the entry point.
It is recommended to set the profit in the ratio 1:1, 1:2,1:3, with partial fixation of 40%, 30%, 30% or wait for the indicator signal (TP)
We recommend fixing positions in parts. There will be a signal in the opposite direction when the volume is released.
To match the risk of the transaction, we recommend that you do not enter with high leverage.
Trade only with the amount that you are willing to lose.
With increased volatility in the market and flat, the indicator can give many signals.
After a strong fall or growth, we recommend not to open positions, because the probability of a flat is high.
✔️ Visualization of entry and exit points
- Entry points (long and short) are graphically displayed. green - long, orange - short
- stop loss levels are marked for clarity of risk management
✔️Recommendations for working with the indicator!
Entry/exit is performed on the next candle after the candle with the signal (buy/sell)
All timeframes and any trading pairs are used (when selecting settings for each one)
The indicator combines several methods of technical analysis:
- work with support and resistance levels
- filtering of signals based on volumes and volatility
- Overbought and oversold analysis using the RSI
- automatic risk management through stop loss
This approach makes the indicator a useful tool for short-term trading and active scalping.
❗️ NO REPAINT ! ❗️






















