Macroeconomic Artificial Neural Networks
This script was created by training 20 selected macroeconomic data to construct artificial neural networks on the S&P 500 index.
No technical analysis data were used.
The average error rate is 0.01.
In this respect, there is a strong relationship between the index and macroeconomic data.
Although it affects the whole world,I personally recommend using it under the following conditions: S&P 500 and related ETFs in 1W time-frame (TF = 1W SPX500USD, SP1!, SPY, SPX etc. )
Macroeconomic Parameters
Effective Federal Funds Rate (FEDFUNDS)
Initial Claims (ICSA)
Civilian Unemployment Rate (UNRATE)
10 Year Treasury Constant Maturity Rate (DGS10)
Gross Domestic Product , 1 Decimal (GDP)
Trade Weighted US Dollar Index : Major Currencies (DTWEXM)
Consumer Price Index For All Urban Consumers (CPIAUCSL)
M1 Money Stock (M1)
M2 Money Stock (M2)
2 - Year Treasury Constant Maturity Rate (DGS2)
30 Year Treasury Constant Maturity Rate (DGS30)
Industrial Production Index (INDPRO)
5-Year Treasury Constant Maturity Rate (FRED : DGS5)
Light Weight Vehicle Sales: Autos and Light Trucks (ALTSALES)
Civilian Employment Population Ratio (EMRATIO)
Capacity Utilization (TOTAL INDUSTRY) (TCU)
Average (Mean) Duration Of Unemployment (UEMPMEAN)
Manufacturing Employment Index (MAN_EMPL)
Manufacturers' New Orders (NEWORDER)
ISM Manufacturing Index (MAN : PMI)
Artificial Neural Network (ANN) Training Details :
Learning cycles: 16231
AutoSave cycles: 100
Grid
Input columns: 19
Output columns: 1
Excluded columns: 0
Training example rows: 998
Validating example rows: 0
Querying example rows: 0
Excluded example rows: 0
Duplicated example rows: 0
Network
Input nodes connected: 19
Hidden layer 1 nodes: 2
Hidden layer 2 nodes: 0
Hidden layer 3 nodes: 0
Output nodes: 1
Controls
Learning rate: 0.1000
Momentum: 0.8000 (Optimized)
Target error: 0.0100
Training error: 0.010000
NOTE : Alerts added . The red histogram represents the bear market and the green histogram represents the bull market.
Bars subject to region changes are shown as background colors. (Teal = Bull , Maroon = Bear Market )
I hope it will be useful in your studies and analysis, regards.
Recherche dans les scripts pour "标准普尔500指数"
Damped Sine Wave Weighted FilterIntroduction
Remember that we can make filters by using convolution, that is summing the product between the input and the filter coefficients, the set of filter coefficients is sometime denoted "kernel", those coefficients can be a same value (simple moving average), a linear function (linearly weighted moving average), a gaussian function (gaussian filter), a polynomial function (lsma of degree p with p = order of the polynomial), you can make many types of kernels, note however that it is easy to fall into the redundancy trap.
Today a low-lag filter who weight the price with a damped sine wave is proposed, the filter characteristics are discussed below.
A Damped Sine Wave
A damped sine wave is a like a sine wave with the difference that the sine wave peak amplitude decay over time.
A damped sine wave
Used Kernel
We use a damped sine wave of period length as kernel.
The coefficients underweight older values which allow the filter to reduce lag.
Step Response
Because the filter has overshoot in the step response we can conclude that there are frequencies amplified in the passband, we could have reached to this conclusion by simply seeing the negative values in the kernel or the "zero-lag" effect on the closing price.
Enough ! We Want To See The Filter !
I should indeed stop bothering you with transient responses but its always good to see how the filter act on simpler signals before seeing it on the closing price. The filter has low-lag and can be used as input for other indicators
Filter with length = 100 as input for the rsi.
The bands trailing stop utility using rolling squared mean average error with length 500 using the filter of length 500 as input.
Approximating A Least Squares Moving Average
A least squares moving average has a linear kernel with certain values under 0, a lsma of length k can be approximated using the proposed filter using period p where p = k + k/4 .
Proposed filter (red) with length = 250 and lsma (blue) with length = 200.
Conclusions
The use of damping in filter design can provide extremely useful filters, in fact the ideal kernel, the sinc function, is also a damped sine wave.
VIX reversion-Buschi
English:
A significant intraday reversion (commonly used: 3 points) on a high (over 20 points) S&P 500 Volatility Index (VIX) can be a sign of a market bottom, because there is the assumption that some of the "big guys" liquidated their options / insurances because the worst is over.
This indicator shows these reversions (3 points as default) when the VIX was over 20 points. The character "R" is then shown directly over the daily column, the VIX need not to be loaded explicitly.
Deutsch:
Eine deutliche Intraday-Umkehr (3 Punkte im Normalfall) bei einem hohen (über 20 Punkte) S&P 500 Volatility Index (VIX) kann ein Zeichen für eine Bodenbildung im Markt sein, weil möglicherweise einige "große Jungs" ihre Optionen / Versicherungen auflösen, weil das schlimmste vorbei ist.
Dieser Indikator zeigt diese Umkehr (Standardwert: 3 Punkte), wenn der VIX vorher über 20 Punkte lag. Der Buchstabe "R" wird dabei direkt über dem Tagesbalken angezeigt, wobei der VIX nicht explizit geladen werden muss.
Relative Price StrengthThe strength of a stock relative to the S&P 500 is key part of most traders decision making process. Hence the default reference security is SPY, the most commonly trades S&P 500 ETF.
Most profitable traders buy stocks that are showing persistence intermediate strength verses the S&P as this has been shown to work. Hence the default period is 63 days or 3 months.
TICK Extremes IndicatorSimple TICK indicator, plots candles and HL2 line
Conditional green/red coloring for highs above 500, 900 and lows above 0, and for lows below -500, -900, and highs above 0
Probably best used for 1 - 5 min timeframes
Always open to suggestions if criteria needs tweaking or if something else would make it more useful or user-friendly!
Market direction and pullback based on S&P 500.A simple indicator based on www.swing-trade-stocks.com The link is also the guide for how to use it.
0 - nothing. If the indicator is showing 0 for a prolonged amount of time, it is likely the market is in "momentum mode" (referred to in the link above).
1 - indicates an uptrend based on SMA and EMA and also a place where a reversal to the upside is likely to occur. You should look only for long trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
-1 - indicates a downtrend based on SMA and EMA and also a place where a reversal to the downside is likely to occur. You should look only for short trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
Net XRP Margin PositionTotal XRP Longs minus XRP Shorts in order to give you the total outstanding XRP margin debt.
ie: If 500,000 XRP has been longed, and 400,000 XRP has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 XRP (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
Net DASH Margin PositionTotal DASH Longs minus DASH Shorts in order to give you the total outstanding DASH margin debt.
ie: If 500,000 DASH has been longed, and 400,000 DASH has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 DASH (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
(Anyone know what category this script should be in?)
Net NEO Margin PositionTotal NEO Longs minus NEO Shorts in order to give you the total outstanding NEO margin debt.
ie: If 500,000 NEO has been longed, and 400,000 NEO has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 NEO (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
(Anyone know what category this script should be in?)
Everyday 0002 _ MAC 1st Trading Hour WalkoverThis is the second strategy for my Everyday project.
Like I wrote the last time - my goal is to create a new strategy everyday
for the rest of 2016 and post it here on TradingView.
I'm a complete beginner so this is my way of learning about coding strategies.
I'll give myself between 15 minutes and 2 hours to complete each creation.
This is basically a repetition of the first strategy I wrote - a Moving Average Crossover,
but I added a tiny thing.
I read that "Statistics have proven that the daily high or low is established within the first hour of trading on more than 70% of the time."
(source: )
My first Moving Average Crossover strategy, tested on VOLVB daily, got stoped out by the volatility
and because of this missed one nice bull run and a very nice bear run.
So I added this single line: if time("60", "1000-1600") regarding when to take exits:
if time("60", "1000-1600")
strategy.exit("Close Long", "Long", profit=2000, loss=500)
strategy.exit("Close Short", "Short", profit=2000, loss=500)
Sweden is UTC+2 so I guess UTC 1000 equals 12.00 in Stockholm. Not sure if this is correct, actually.
Anyway, I hope this means the strategy will only take exits based on price action which occur in the afternoon, when there is a higher probability of a lower volatility.
When I ran the new modified strategy on the same VOLVB daily it didn't get stoped out so easily.
On the other hand I'll have to test this on various stocks .
Reading and learning about how to properly test strategies is on my todo list - all tips on youtube videos or blogs
to read on this topic is very welcome!
Like I said the last time, I'm posting these strategies hoping to learn from the community - so any feedback, advice, or corrections is very much welcome and appreciated!
/pbergden
Quantum Rotational Field MappingQuantum Rotational Field Mapping (QRFM):
Phase Coherence Detection Through Complex-Plane Oscillator Analysis
Quantum Rotational Field Mapping applies complex-plane mathematics and phase-space analysis to oscillator ensembles, identifying high-probability trend ignition points by measuring when multiple independent oscillators achieve phase coherence. Unlike traditional multi-oscillator approaches that simply stack indicators or use boolean AND/OR logic, this system converts each oscillator into a rotating phasor (vector) in the complex plane and calculates the Coherence Index (CI) —a mathematical measure of how tightly aligned the ensemble has become—then generates signals only when alignment, phase direction, and pairwise entanglement all converge.
The indicator combines three mathematical frameworks: phasor representation using analytic signal theory to extract phase and amplitude from each oscillator, coherence measurement using vector summation in the complex plane to quantify group alignment, and entanglement analysis that calculates pairwise phase agreement across all oscillator combinations. This creates a multi-dimensional confirmation system that distinguishes between random oscillator noise and genuine regime transitions.
What Makes This Original
Complex-Plane Phasor Framework
This indicator implements classical signal processing mathematics adapted for market oscillators. Each oscillator—whether RSI, MACD, Stochastic, CCI, Williams %R, MFI, ROC, or TSI—is first normalized to a common scale, then converted into a complex-plane representation using an in-phase (I) and quadrature (Q) component. The in-phase component is the oscillator value itself, while the quadrature component is calculated as the first difference (derivative proxy), creating a velocity-aware representation.
From these components, the system extracts:
Phase (φ) : Calculated as φ = atan2(Q, I), representing the oscillator's position in its cycle (mapped to -180° to +180°)
Amplitude (A) : Calculated as A = √(I² + Q²), representing the oscillator's strength or conviction
This mathematical approach is fundamentally different from simply reading oscillator values. A phasor captures both where an oscillator is in its cycle (phase angle) and how strongly it's expressing that position (amplitude). Two oscillators can have the same value but be in opposite phases of their cycles—traditional analysis would see them as identical, while QRFM sees them as 180° out of phase (contradictory).
Coherence Index Calculation
The core innovation is the Coherence Index (CI) , borrowed from physics and signal processing. When you have N oscillators, each with phase φₙ, you can represent each as a unit vector in the complex plane: e^(iφₙ) = cos(φₙ) + i·sin(φₙ).
The CI measures what happens when you sum all these vectors:
Resultant Vector : R = Σ e^(iφₙ) = Σ cos(φₙ) + i·Σ sin(φₙ)
Coherence Index : CI = |R| / N
Where |R| is the magnitude of the resultant vector and N is the number of active oscillators.
The CI ranges from 0 to 1:
CI = 1.0 : Perfect coherence—all oscillators have identical phase angles, vectors point in the same direction, creating maximum constructive interference
CI = 0.0 : Complete decoherence—oscillators are randomly distributed around the circle, vectors cancel out through destructive interference
0 < CI < 1 : Partial alignment—some clustering with some scatter
This is not a simple average or correlation. The CI captures phase synchronization across the entire ensemble simultaneously. When oscillators phase-lock (align their cycles), the CI spikes regardless of their individual values. This makes it sensitive to regime transitions that traditional indicators miss.
Dominant Phase and Direction Detection
Beyond measuring alignment strength, the system calculates the dominant phase of the ensemble—the direction the resultant vector points:
Dominant Phase : φ_dom = atan2(Σ sin(φₙ), Σ cos(φₙ))
This gives the "average direction" of all oscillator phases, mapped to -180° to +180°:
+90° to -90° (right half-plane): Bullish phase dominance
+90° to +180° or -90° to -180° (left half-plane): Bearish phase dominance
The combination of CI magnitude (coherence strength) and dominant phase angle (directional bias) creates a two-dimensional signal space. High CI alone is insufficient—you need high CI plus dominant phase pointing in a tradeable direction. This dual requirement is what separates QRFM from simple oscillator averaging.
Entanglement Matrix and Pairwise Coherence
While the CI measures global alignment, the entanglement matrix measures local pairwise relationships. For every pair of oscillators (i, j), the system calculates:
E(i,j) = |cos(φᵢ - φⱼ)|
This represents the phase agreement between oscillators i and j:
E = 1.0 : Oscillators are in-phase (0° or 360° apart)
E = 0.0 : Oscillators are in quadrature (90° apart, orthogonal)
E between 0 and 1 : Varying degrees of alignment
The system counts how many oscillator pairs exceed a user-defined entanglement threshold (e.g., 0.7). This entangled pairs count serves as a confirmation filter: signals require not just high global CI, but also a minimum number of strong pairwise agreements. This prevents false ignitions where CI is high but driven by only two oscillators while the rest remain scattered.
The entanglement matrix creates an N×N symmetric matrix that can be visualized as a web—when many cells are bright (high E values), the ensemble is highly interconnected. When cells are dark, oscillators are moving independently.
Phase-Lock Tolerance Mechanism
A complementary confirmation layer is the phase-lock detector . This calculates the maximum phase spread across all oscillators:
For all pairs (i,j), compute angular distance: Δφ = |φᵢ - φⱼ|, wrapping at 180°
Max Spread = maximum Δφ across all pairs
If max spread < user threshold (e.g., 35°), the ensemble is considered phase-locked —all oscillators are within a narrow angular band.
This differs from entanglement: entanglement measures pairwise cosine similarity (magnitude of alignment), while phase-lock measures maximum angular deviation (tightness of clustering). Both must be satisfied for the highest-conviction signals.
Multi-Layer Visual Architecture
QRFM includes six visual components that represent the same underlying mathematics from different perspectives:
Circular Orbit Plot : A polar coordinate grid showing each oscillator as a vector from origin to perimeter. Angle = phase, radius = amplitude. This is a real-time snapshot of the complex plane. When vectors converge (point in similar directions), coherence is high. When scattered randomly, coherence is low. Users can see phase alignment forming before CI numerically confirms it.
Phase-Time Heat Map : A 2D matrix with rows = oscillators and columns = time bins. Each cell is colored by the oscillator's phase at that time (using a gradient where color hue maps to angle). Horizontal color bands indicate sustained phase alignment over time. Vertical color bands show moments when all oscillators shared the same phase (ignition points). This provides historical pattern recognition.
Entanglement Web Matrix : An N×N grid showing E(i,j) for all pairs. Cells are colored by entanglement strength—bright yellow/gold for high E, dark gray for low E. This reveals which oscillators are driving coherence and which are lagging. For example, if RSI and MACD show high E but Stochastic shows low E with everything, Stochastic is the outlier.
Quantum Field Cloud : A background color overlay on the price chart. Color (green = bullish, red = bearish) is determined by dominant phase. Opacity is determined by CI—high CI creates dense, opaque cloud; low CI creates faint, nearly invisible cloud. This gives an atmospheric "feel" for regime strength without looking at numbers.
Phase Spiral : A smoothed plot of dominant phase over recent history, displayed as a curve that wraps around price. When the spiral is tight and rotating steadily, the ensemble is in coherent rotation (trending). When the spiral is loose or erratic, coherence is breaking down.
Dashboard : A table showing real-time metrics: CI (as percentage), dominant phase (in degrees with directional arrow), field strength (CI × average amplitude), entangled pairs count, phase-lock status (locked/unlocked), quantum state classification ("Ignition", "Coherent", "Collapse", "Chaos"), and collapse risk (recent CI change normalized to 0-100%).
Each component is independently toggleable, allowing users to customize their workspace. The orbit plot is the most essential—it provides intuitive, visual feedback on phase alignment that no numerical dashboard can match.
Core Components and How They Work Together
1. Oscillator Normalization Engine
The foundation is creating a common measurement scale. QRFM supports eight oscillators:
RSI : Normalized from to using overbought/oversold levels (70, 30) as anchors
MACD Histogram : Normalized by dividing by rolling standard deviation, then clamped to
Stochastic %K : Normalized from using (80, 20) anchors
CCI : Divided by 200 (typical extreme level), clamped to
Williams %R : Normalized from using (-20, -80) anchors
MFI : Normalized from using (80, 20) anchors
ROC : Divided by 10, clamped to
TSI : Divided by 50, clamped to
Each oscillator can be individually enabled/disabled. Only active oscillators contribute to phase calculations. The normalization removes scale differences—a reading of +0.8 means "strongly bullish" regardless of whether it came from RSI or TSI.
2. Analytic Signal Construction
For each active oscillator at each bar, the system constructs the analytic signal:
In-Phase (I) : The normalized oscillator value itself
Quadrature (Q) : The bar-to-bar change in the normalized value (first derivative approximation)
This creates a 2D representation: (I, Q). The phase is extracted as:
φ = atan2(Q, I) × (180 / π)
This maps the oscillator to a point on the unit circle. An oscillator at the same value but rising (positive Q) will have a different phase than one that is falling (negative Q). This velocity-awareness is critical—it distinguishes between "at resistance and stalling" versus "at resistance and breaking through."
The amplitude is extracted as:
A = √(I² + Q²)
This represents the distance from origin in the (I, Q) plane. High amplitude means the oscillator is far from neutral (strong conviction). Low amplitude means it's near zero (weak/transitional state).
3. Coherence Calculation Pipeline
For each bar (or every Nth bar if phase sample rate > 1 for performance):
Step 1 : Extract phase φₙ for each of the N active oscillators
Step 2 : Compute complex exponentials: Zₙ = e^(i·φₙ·π/180) = cos(φₙ·π/180) + i·sin(φₙ·π/180)
Step 3 : Sum the complex exponentials: R = Σ Zₙ = (Σ cos φₙ) + i·(Σ sin φₙ)
Step 4 : Calculate magnitude: |R| = √
Step 5 : Normalize by count: CI_raw = |R| / N
Step 6 : Smooth the CI: CI = SMA(CI_raw, smoothing_window)
The smoothing step (default 2 bars) removes single-bar noise spikes while preserving structural coherence changes. Users can adjust this to control reactivity versus stability.
The dominant phase is calculated as:
φ_dom = atan2(Σ sin φₙ, Σ cos φₙ) × (180 / π)
This is the angle of the resultant vector R in the complex plane.
4. Entanglement Matrix Construction
For all unique pairs of oscillators (i, j) where i < j:
Step 1 : Get phases φᵢ and φⱼ
Step 2 : Compute phase difference: Δφ = φᵢ - φⱼ (in radians)
Step 3 : Calculate entanglement: E(i,j) = |cos(Δφ)|
Step 4 : Store in symmetric matrix: matrix = matrix = E(i,j)
The matrix is then scanned: count how many E(i,j) values exceed the user-defined threshold (default 0.7). This count is the entangled pairs metric.
For visualization, the matrix is rendered as an N×N table where cell brightness maps to E(i,j) intensity.
5. Phase-Lock Detection
Step 1 : For all unique pairs (i, j), compute angular distance: Δφ = |φᵢ - φⱼ|
Step 2 : Wrap angles: if Δφ > 180°, set Δφ = 360° - Δφ
Step 3 : Find maximum: max_spread = max(Δφ) across all pairs
Step 4 : Compare to tolerance: phase_locked = (max_spread < tolerance)
If phase_locked is true, all oscillators are within the specified angular cone (e.g., 35°). This is a boolean confirmation filter.
6. Signal Generation Logic
Signals are generated through multi-layer confirmation:
Long Ignition Signal :
CI crosses above ignition threshold (e.g., 0.80)
AND dominant phase is in bullish range (-90° < φ_dom < +90°)
AND phase_locked = true
AND entangled_pairs >= minimum threshold (e.g., 4)
Short Ignition Signal :
CI crosses above ignition threshold
AND dominant phase is in bearish range (φ_dom < -90° OR φ_dom > +90°)
AND phase_locked = true
AND entangled_pairs >= minimum threshold
Collapse Signal :
CI at bar minus CI at current bar > collapse threshold (e.g., 0.55)
AND CI at bar was above 0.6 (must collapse from coherent state, not from already-low state)
These are strict conditions. A high CI alone does not generate a signal—dominant phase must align with direction, oscillators must be phase-locked, and sufficient pairwise entanglement must exist. This multi-factor gating dramatically reduces false signals compared to single-condition triggers.
Calculation Methodology
Phase 1: Oscillator Computation and Normalization
On each bar, the system calculates the raw values for all enabled oscillators using standard Pine Script functions:
RSI: ta.rsi(close, length)
MACD: ta.macd() returning histogram component
Stochastic: ta.stoch() smoothed with ta.sma()
CCI: ta.cci(close, length)
Williams %R: ta.wpr(length)
MFI: ta.mfi(hlc3, length)
ROC: ta.roc(close, length)
TSI: ta.tsi(close, short, long)
Each raw value is then passed through a normalization function:
normalize(value, overbought_level, oversold_level) = 2 × (value - oversold) / (overbought - oversold) - 1
This maps the oscillator's typical range to , where -1 represents extreme bearish, 0 represents neutral, and +1 represents extreme bullish.
For oscillators without fixed ranges (MACD, ROC, TSI), statistical normalization is used: divide by a rolling standard deviation or fixed divisor, then clamp to .
Phase 2: Phasor Extraction
For each normalized oscillator value val:
I = val (in-phase component)
Q = val - val (quadrature component, first difference)
Phase calculation:
phi_rad = atan2(Q, I)
phi_deg = phi_rad × (180 / π)
Amplitude calculation:
A = √(I² + Q²)
These values are stored in arrays: osc_phases and osc_amps for each oscillator n.
Phase 3: Complex Summation and Coherence
Initialize accumulators:
sum_cos = 0
sum_sin = 0
For each oscillator n = 0 to N-1:
phi_rad = osc_phases × (π / 180)
sum_cos += cos(phi_rad)
sum_sin += sin(phi_rad)
Resultant magnitude:
resultant_mag = √(sum_cos² + sum_sin²)
Coherence Index (raw):
CI_raw = resultant_mag / N
Smoothed CI:
CI = SMA(CI_raw, smoothing_window)
Dominant phase:
phi_dom_rad = atan2(sum_sin, sum_cos)
phi_dom_deg = phi_dom_rad × (180 / π)
Phase 4: Entanglement Matrix Population
For i = 0 to N-2:
For j = i+1 to N-1:
phi_i = osc_phases × (π / 180)
phi_j = osc_phases × (π / 180)
delta_phi = phi_i - phi_j
E = |cos(delta_phi)|
matrix_index_ij = i × N + j
matrix_index_ji = j × N + i
entangle_matrix = E
entangle_matrix = E
if E >= threshold:
entangled_pairs += 1
The matrix uses flat array storage with index mapping: index(row, col) = row × N + col.
Phase 5: Phase-Lock Check
max_spread = 0
For i = 0 to N-2:
For j = i+1 to N-1:
delta = |osc_phases - osc_phases |
if delta > 180:
delta = 360 - delta
max_spread = max(max_spread, delta)
phase_locked = (max_spread < tolerance)
Phase 6: Signal Evaluation
Ignition Long :
ignition_long = (CI crosses above threshold) AND
(phi_dom > -90 AND phi_dom < 90) AND
phase_locked AND
(entangled_pairs >= minimum)
Ignition Short :
ignition_short = (CI crosses above threshold) AND
(phi_dom < -90 OR phi_dom > 90) AND
phase_locked AND
(entangled_pairs >= minimum)
Collapse :
CI_prev = CI
collapse = (CI_prev - CI > collapse_threshold) AND (CI_prev > 0.6)
All signals are evaluated on bar close. The crossover and crossunder functions ensure signals fire only once when conditions transition from false to true.
Phase 7: Field Strength and Visualization Metrics
Average Amplitude :
avg_amp = (Σ osc_amps ) / N
Field Strength :
field_strength = CI × avg_amp
Collapse Risk (for dashboard):
collapse_risk = (CI - CI) / max(CI , 0.1)
collapse_risk_pct = clamp(collapse_risk × 100, 0, 100)
Quantum State Classification :
if (CI > threshold AND phase_locked):
state = "Ignition"
else if (CI > 0.6):
state = "Coherent"
else if (collapse):
state = "Collapse"
else:
state = "Chaos"
Phase 8: Visual Rendering
Orbit Plot : For each oscillator, convert polar (phase, amplitude) to Cartesian (x, y) for grid placement:
radius = amplitude × grid_center × 0.8
x = radius × cos(phase × π/180)
y = radius × sin(phase × π/180)
col = center + x (mapped to grid coordinates)
row = center - y
Heat Map : For each oscillator row and time column, retrieve historical phase value at lookback = (columns - col) × sample_rate, then map phase to color using a hue gradient.
Entanglement Web : Render matrix as table cell with background color opacity = E(i,j).
Field Cloud : Background color = (phi_dom > -90 AND phi_dom < 90) ? green : red, with opacity = mix(min_opacity, max_opacity, CI).
All visual components render only on the last bar (barstate.islast) to minimize computational overhead.
How to Use This Indicator
Step 1 : Apply QRFM to your chart. It works on all timeframes and asset classes, though 15-minute to 4-hour timeframes provide the best balance of responsiveness and noise reduction.
Step 2 : Enable the dashboard (default: top right) and the circular orbit plot (default: middle left). These are your primary visual feedback tools.
Step 3 : Optionally enable the heat map, entanglement web, and field cloud based on your preference. New users may find all visuals overwhelming; start with dashboard + orbit plot.
Step 4 : Observe for 50-100 bars to let the indicator establish baseline coherence patterns. Markets have different "normal" CI ranges—some instruments naturally run higher or lower coherence.
Understanding the Circular Orbit Plot
The orbit plot is a polar grid showing oscillator vectors in real-time:
Center point : Neutral (zero phase and amplitude)
Each vector : A line from center to a point on the grid
Vector angle : The oscillator's phase (0° = right/east, 90° = up/north, 180° = left/west, -90° = down/south)
Vector length : The oscillator's amplitude (short = weak signal, long = strong signal)
Vector label : First letter of oscillator name (R = RSI, M = MACD, etc.)
What to watch :
Convergence : When all vectors cluster in one quadrant or sector, CI is rising and coherence is forming. This is your pre-signal warning.
Scatter : When vectors point in random directions (360° spread), CI is low and the market is in a non-trending or transitional regime.
Rotation : When the cluster rotates smoothly around the circle, the ensemble is in coherent oscillation—typically seen during steady trends.
Sudden flips : When the cluster rapidly jumps from one side to the opposite (e.g., +90° to -90°), a phase reversal has occurred—often coinciding with trend reversals.
Example: If you see RSI, MACD, and Stochastic all pointing toward 45° (northeast) with long vectors, while CCI, TSI, and ROC point toward 40-50° as well, coherence is high and dominant phase is bullish. Expect an ignition signal if CI crosses threshold.
Reading Dashboard Metrics
The dashboard provides numerical confirmation of what the orbit plot shows visually:
CI : Displays as 0-100%. Above 70% = high coherence (strong regime), 40-70% = moderate, below 40% = low (poor conditions for trend entries).
Dom Phase : Angle in degrees with directional arrow. ⬆ = bullish bias, ⬇ = bearish bias, ⬌ = neutral.
Field Strength : CI weighted by amplitude. High values (> 0.6) indicate not just alignment but strong alignment.
Entangled Pairs : Count of oscillator pairs with E > threshold. Higher = more confirmation. If minimum is set to 4, you need at least 4 pairs entangled for signals.
Phase Lock : 🔒 YES (all oscillators within tolerance) or 🔓 NO (spread too wide).
State : Real-time classification:
🚀 IGNITION: CI just crossed threshold with phase-lock
⚡ COHERENT: CI is high and stable
💥 COLLAPSE: CI has dropped sharply
🌀 CHAOS: Low CI, scattered phases
Collapse Risk : 0-100% scale based on recent CI change. Above 50% warns of imminent breakdown.
Interpreting Signals
Long Ignition (Blue Triangle Below Price) :
Occurs when CI crosses above threshold (e.g., 0.80)
Dominant phase is in bullish range (-90° to +90°)
All oscillators are phase-locked (within tolerance)
Minimum entangled pairs requirement met
Interpretation : The oscillator ensemble has transitioned from disorder to coherent bullish alignment. This is a high-probability long entry point. The multi-layer confirmation (CI + phase direction + lock + entanglement) ensures this is not a single-oscillator whipsaw.
Short Ignition (Red Triangle Above Price) :
Same conditions as long, but dominant phase is in bearish range (< -90° or > +90°)
Interpretation : Coherent bearish alignment has formed. High-probability short entry.
Collapse (Circles Above and Below Price) :
CI has dropped by more than the collapse threshold (e.g., 0.55) over a 5-bar window
CI was previously above 0.6 (collapsing from coherent state)
Interpretation : Phase coherence has broken down. If you are in a position, this is an exit warning. If looking to enter, stand aside—regime is transitioning.
Phase-Time Heat Map Patterns
Enable the heat map and position it at bottom right. The rows represent individual oscillators, columns represent time bins (most recent on left).
Pattern: Horizontal Color Bands
If a row (e.g., RSI) shows consistent color across columns (say, green for several bins), that oscillator has maintained stable phase over time. If all rows show horizontal bands of similar color, the entire ensemble has been phase-locked for an extended period—this is a strong trending regime.
Pattern: Vertical Color Bands
If a column (single time bin) shows all cells with the same or very similar color, that moment in time had high coherence. These vertical bands often align with ignition signals or major price pivots.
Pattern: Rainbow Chaos
If cells are random colors (red, green, yellow mixed with no pattern), coherence is low. The ensemble is scattered. Avoid trading during these periods unless you have external confirmation.
Pattern: Color Transition
If you see a row transition from red to green (or vice versa) sharply, that oscillator has phase-flipped. If multiple rows do this simultaneously, a regime change is underway.
Entanglement Web Analysis
Enable the web matrix (default: opposite corner from heat map). It shows an N×N grid where N = number of active oscillators.
Bright Yellow/Gold Cells : High pairwise entanglement. For example, if the RSI-MACD cell is bright gold, those two oscillators are moving in phase. If the RSI-Stochastic cell is bright, they are entangled as well.
Dark Gray Cells : Low entanglement. Oscillators are decorrelated or in quadrature.
Diagonal : Always marked with "—" because an oscillator is always perfectly entangled with itself.
How to use :
Scan for clustering: If most cells are bright, coherence is high across the board. If only a few cells are bright, coherence is driven by a subset (e.g., RSI and MACD are aligned, but nothing else is—weak signal).
Identify laggards: If one row/column is entirely dark, that oscillator is the outlier. You may choose to disable it or monitor for when it joins the group (late confirmation).
Watch for web formation: During low-coherence periods, the matrix is mostly dark. As coherence builds, cells begin lighting up. A sudden "web" of connections forming visually precedes ignition signals.
Trading Workflow
Step 1: Monitor Coherence Level
Check the dashboard CI metric or observe the orbit plot. If CI is below 40% and vectors are scattered, conditions are poor for trend entries. Wait.
Step 2: Detect Coherence Building
When CI begins rising (say, from 30% to 50-60%) and you notice vectors on the orbit plot starting to cluster, coherence is forming. This is your alert phase—do not enter yet, but prepare.
Step 3: Confirm Phase Direction
Check the dominant phase angle and the orbit plot quadrant where clustering is occurring:
Clustering in right half (0° to ±90°): Bullish bias forming
Clustering in left half (±90° to 180°): Bearish bias forming
Verify the dashboard shows the corresponding directional arrow (⬆ or ⬇).
Step 4: Wait for Signal Confirmation
Do not enter based on rising CI alone. Wait for the full ignition signal:
CI crosses above threshold
Phase-lock indicator shows 🔒 YES
Entangled pairs count >= minimum
Directional triangle appears on chart
This ensures all layers have aligned.
Step 5: Execute Entry
Long : Blue triangle below price appears → enter long
Short : Red triangle above price appears → enter short
Step 6: Position Management
Initial Stop : Place stop loss based on your risk management rules (e.g., recent swing low/high, ATR-based buffer).
Monitoring :
Watch the field cloud density. If it remains opaque and colored in your direction, the regime is intact.
Check dashboard collapse risk. If it rises above 50%, prepare for exit.
Monitor the orbit plot. If vectors begin scattering or the cluster flips to the opposite side, coherence is breaking.
Exit Triggers :
Collapse signal fires (circles appear)
Dominant phase flips to opposite half-plane
CI drops below 40% (coherence lost)
Price hits your profit target or trailing stop
Step 7: Post-Exit Analysis
After exiting, observe whether a new ignition forms in the opposite direction (reversal) or if CI remains low (transition to range). Use this to decide whether to re-enter, reverse, or stand aside.
Best Practices
Use Price Structure as Context
QRFM identifies when coherence forms but does not specify where price will go. Combine ignition signals with support/resistance levels, trendlines, or chart patterns. For example:
Long ignition near a major support level after a pullback: high-probability bounce
Long ignition in the middle of a range with no structure: lower probability
Multi-Timeframe Confirmation
Open QRFM on two timeframes simultaneously:
Higher timeframe (e.g., 4-hour): Use CI level to determine regime bias. If 4H CI is above 60% and dominant phase is bullish, the market is in a bullish regime.
Lower timeframe (e.g., 15-minute): Execute entries on ignition signals that align with the higher timeframe bias.
This prevents counter-trend trades and increases win rate.
Distinguish Between Regime Types
High CI, stable dominant phase (State: Coherent) : Trending market. Ignitions are continuation signals; collapses are profit-taking or reversal warnings.
Low CI, erratic dominant phase (State: Chaos) : Ranging or choppy market. Avoid ignition signals or reduce position size. Wait for coherence to establish.
Moderate CI with frequent collapses : Whipsaw environment. Use wider stops or stand aside.
Adjust Parameters to Instrument and Timeframe
Crypto/Forex (high volatility) : Lower ignition threshold (0.65-0.75), lower CI smoothing (2-3), shorter oscillator lengths (7-10).
Stocks/Indices (moderate volatility) : Standard settings (threshold 0.75-0.85, smoothing 5-7, oscillator lengths 14).
Lower timeframes (5-15 min) : Reduce phase sample rate to 1-2 for responsiveness.
Higher timeframes (daily+) : Increase CI smoothing and oscillator lengths for noise reduction.
Use Entanglement Count as Conviction Filter
The minimum entangled pairs setting controls signal strictness:
Low (1-2) : More signals, lower quality (acceptable if you have other confirmation)
Medium (3-5) : Balanced (recommended for most traders)
High (6+) : Very strict, fewer signals, highest quality
Adjust based on your trade frequency preference and risk tolerance.
Monitor Oscillator Contribution
Use the entanglement web to see which oscillators are driving coherence. If certain oscillators are consistently dark (low E with all others), they may be adding noise. Consider disabling them. For example:
On low-volume instruments, MFI may be unreliable → disable MFI
On strongly trending instruments, mean-reversion oscillators (Stochastic, RSI) may lag → reduce weight or disable
Respect the Collapse Signal
Collapse events are early warnings. Price may continue in the original direction for several bars after collapse fires, but the underlying regime has weakened. Best practice:
If in profit: Take partial or full profit on collapse
If at breakeven/small loss: Exit immediately
If collapse occurs shortly after entry: Likely a false ignition; exit to avoid drawdown
Collapses do not guarantee immediate reversals—they signal uncertainty .
Combine with Volume Analysis
If your instrument has reliable volume:
Ignitions with expanding volume: Higher conviction
Ignitions with declining volume: Weaker, possibly false
Collapses with volume spikes: Strong reversal signal
Collapses with low volume: May just be consolidation
Volume is not built into QRFM (except via MFI), so add it as external confirmation.
Observe the Phase Spiral
The spiral provides a quick visual cue for rotation consistency:
Tight, smooth spiral : Ensemble is rotating coherently (trending)
Loose, erratic spiral : Phase is jumping around (ranging or transitional)
If the spiral tightens, coherence is building. If it loosens, coherence is dissolving.
Do Not Overtrade Low-Coherence Periods
When CI is persistently below 40% and the state is "Chaos," the market is not in a regime where phase analysis is predictive. During these times:
Reduce position size
Widen stops
Wait for coherence to return
QRFM's strength is regime detection. If there is no regime, the tool correctly signals "stand aside."
Use Alerts Strategically
Set alerts for:
Long Ignition
Short Ignition
Collapse
Phase Lock (optional)
Configure alerts to "Once per bar close" to avoid intrabar repainting and noise. When an alert fires, manually verify:
Orbit plot shows clustering
Dashboard confirms all conditions
Price structure supports the trade
Do not blindly trade alerts—use them as prompts for analysis.
Ideal Market Conditions
Best Performance
Instruments :
Liquid, actively traded markets (major forex pairs, large-cap stocks, major indices, top-tier crypto)
Instruments with clear cyclical oscillator behavior (avoid extremely illiquid or manipulated markets)
Timeframes :
15-minute to 4-hour: Optimal balance of noise reduction and responsiveness
1-hour to daily: Slower, higher-conviction signals; good for swing trading
5-minute: Acceptable for scalping if parameters are tightened and you accept more noise
Market Regimes :
Trending markets with periodic retracements (where oscillators cycle through phases predictably)
Breakout environments (coherence forms before/during breakout; collapse occurs at exhaustion)
Rotational markets with clear swings (oscillators phase-lock at turning points)
Volatility :
Moderate to high volatility (oscillators have room to move through their ranges)
Stable volatility regimes (sudden VIX spikes or flash crashes may create false collapses)
Challenging Conditions
Instruments :
Very low liquidity markets (erratic price action creates unstable oscillator phases)
Heavily news-driven instruments (fundamentals may override technical coherence)
Highly correlated instruments (oscillators may all reflect the same underlying factor, reducing independence)
Market Regimes :
Deep, prolonged consolidation (oscillators remain near neutral, CI is chronically low, few signals fire)
Extreme chop with no directional bias (oscillators whipsaw, coherence never establishes)
Gap-driven markets (large overnight gaps create phase discontinuities)
Timeframes :
Sub-5-minute charts: Noise dominates; oscillators flip rapidly; coherence is fleeting and unreliable
Weekly/monthly: Oscillators move extremely slowly; signals are rare; better suited for long-term positioning than active trading
Special Cases :
During major economic releases or earnings: Oscillators may lag price or become decorrelated as fundamentals overwhelm technicals. Reduce position size or stand aside.
In extremely low-volatility environments (e.g., holiday periods): Oscillators compress to neutral, CI may be artificially high due to lack of movement, but signals lack follow-through.
Adaptive Behavior
QRFM is designed to self-adapt to poor conditions:
When coherence is genuinely absent, CI remains low and signals do not fire
When only a subset of oscillators aligns, entangled pairs count stays below threshold and signals are filtered out
When phase-lock cannot be achieved (oscillators too scattered), the lock filter prevents signals
This means the indicator will naturally produce fewer (or zero) signals during unfavorable conditions, rather than generating false signals. This is a feature —it keeps you out of low-probability trades.
Parameter Optimization by Trading Style
Scalping (5-15 Minute Charts)
Goal : Maximum responsiveness, accept higher noise
Oscillator Lengths :
RSI: 7-10
MACD: 8/17/6
Stochastic: 8-10, smooth 2-3
CCI: 14-16
Others: 8-12
Coherence Settings :
CI Smoothing Window: 2-3 bars (fast reaction)
Phase Sample Rate: 1 (every bar)
Ignition Threshold: 0.65-0.75 (lower for more signals)
Collapse Threshold: 0.40-0.50 (earlier exit warnings)
Confirmation :
Phase Lock Tolerance: 40-50° (looser, easier to achieve)
Min Entangled Pairs: 2-3 (fewer oscillators required)
Visuals :
Orbit Plot + Dashboard only (reduce screen clutter for fast decisions)
Disable heavy visuals (heat map, web) for performance
Alerts :
Enable all ignition and collapse alerts
Set to "Once per bar close"
Day Trading (15-Minute to 1-Hour Charts)
Goal : Balance between responsiveness and reliability
Oscillator Lengths :
RSI: 14 (standard)
MACD: 12/26/9 (standard)
Stochastic: 14, smooth 3
CCI: 20
Others: 10-14
Coherence Settings :
CI Smoothing Window: 3-5 bars (balanced)
Phase Sample Rate: 2-3
Ignition Threshold: 0.75-0.85 (moderate selectivity)
Collapse Threshold: 0.50-0.55 (balanced exit timing)
Confirmation :
Phase Lock Tolerance: 30-40° (moderate tightness)
Min Entangled Pairs: 4-5 (reasonable confirmation)
Visuals :
Orbit Plot + Dashboard + Heat Map or Web (choose one)
Field Cloud for regime backdrop
Alerts :
Ignition and collapse alerts
Optional phase-lock alert for advance warning
Swing Trading (4-Hour to Daily Charts)
Goal : High-conviction signals, minimal noise, fewer trades
Oscillator Lengths :
RSI: 14-21
MACD: 12/26/9 or 19/39/9 (longer variant)
Stochastic: 14-21, smooth 3-5
CCI: 20-30
Others: 14-20
Coherence Settings :
CI Smoothing Window: 5-10 bars (very smooth)
Phase Sample Rate: 3-5
Ignition Threshold: 0.80-0.90 (high bar for entry)
Collapse Threshold: 0.55-0.65 (only significant breakdowns)
Confirmation :
Phase Lock Tolerance: 20-30° (tight clustering required)
Min Entangled Pairs: 5-7 (strong confirmation)
Visuals :
All modules enabled (you have time to analyze)
Heat Map for multi-bar pattern recognition
Web for deep confirmation analysis
Alerts :
Ignition and collapse
Review manually before entering (no rush)
Position/Long-Term Trading (Daily to Weekly Charts)
Goal : Rare, very high-conviction regime shifts
Oscillator Lengths :
RSI: 21-30
MACD: 19/39/9 or 26/52/12
Stochastic: 21, smooth 5
CCI: 30-50
Others: 20-30
Coherence Settings :
CI Smoothing Window: 10-14 bars
Phase Sample Rate: 5 (every 5th bar to reduce computation)
Ignition Threshold: 0.85-0.95 (only extreme alignment)
Collapse Threshold: 0.60-0.70 (major regime breaks only)
Confirmation :
Phase Lock Tolerance: 15-25° (very tight)
Min Entangled Pairs: 6+ (broad consensus required)
Visuals :
Dashboard + Orbit Plot for quick checks
Heat Map to study historical coherence patterns
Web to verify deep entanglement
Alerts :
Ignition only (collapses are less critical on long timeframes)
Manual review with fundamental analysis overlay
Performance Optimization (Low-End Systems)
If you experience lag or slow rendering:
Reduce Visual Load :
Orbit Grid Size: 8-10 (instead of 12+)
Heat Map Time Bins: 5-8 (instead of 10+)
Disable Web Matrix entirely if not needed
Disable Field Cloud and Phase Spiral
Reduce Calculation Frequency :
Phase Sample Rate: 5-10 (calculate every 5-10 bars)
Max History Depth: 100-200 (instead of 500+)
Disable Unused Oscillators :
If you only want RSI, MACD, and Stochastic, disable the other five. Fewer oscillators = smaller matrices, faster loops.
Simplify Dashboard :
Choose "Small" dashboard size
Reduce number of metrics displayed
These settings will not significantly degrade signal quality (signals are based on bar-close calculations, which remain accurate), but will improve chart responsiveness.
Important Disclaimers
This indicator is a technical analysis tool designed to identify periods of phase coherence across an ensemble of oscillators. It is not a standalone trading system and does not guarantee profitable trades. The Coherence Index, dominant phase, and entanglement metrics are mathematical calculations applied to historical price data—they measure past oscillator behavior and do not predict future price movements with certainty.
No Predictive Guarantee : High coherence indicates that oscillators are currently aligned, which historically has coincided with trending or directional price movement. However, past alignment does not guarantee future trends. Markets can remain coherent while prices consolidate, or lose coherence suddenly due to news, liquidity changes, or other factors not captured by oscillator mathematics.
Signal Confirmation is Probabilistic : The multi-layer confirmation system (CI threshold + dominant phase + phase-lock + entanglement) is designed to filter out low-probability setups. This increases the proportion of valid signals relative to false signals, but does not eliminate false signals entirely. Users should combine QRFM with additional analysis—support and resistance levels, volume confirmation, multi-timeframe alignment, and fundamental context—before executing trades.
Collapse Signals are Warnings, Not Reversals : A coherence collapse indicates that the oscillator ensemble has lost alignment. This often precedes trend exhaustion or reversals, but can also occur during healthy pullbacks or consolidations. Price may continue in the original direction after a collapse. Use collapses as risk management cues (tighten stops, take partial profits) rather than automatic reversal entries.
Market Regime Dependency : QRFM performs best in markets where oscillators exhibit cyclical, mean-reverting behavior and where trends are punctuated by retracements. In markets dominated by fundamental shocks, gap openings, or extreme low-liquidity conditions, oscillator coherence may be less reliable. During such periods, reduce position size or stand aside.
Risk Management is Essential : All trading involves risk of loss. Use appropriate stop losses, position sizing, and risk-per-trade limits. The indicator does not specify stop loss or take profit levels—these must be determined by the user based on their risk tolerance and account size. Never risk more than you can afford to lose.
Parameter Sensitivity : The indicator's behavior changes with input parameters. Aggressive settings (low thresholds, loose tolerances) produce more signals with lower average quality. Conservative settings (high thresholds, tight tolerances) produce fewer signals with higher average quality. Users should backtest and forward-test parameter sets on their specific instruments and timeframes before committing real capital.
No Repainting by Design : All signal conditions are evaluated on bar close using bar-close values. However, the visual components (orbit plot, heat map, dashboard) update in real-time during bar formation for monitoring purposes. For trade execution, rely on the confirmed signals (triangles and circles) that appear only after the bar closes.
Computational Load : QRFM performs extensive calculations, including nested loops for entanglement matrices and real-time table rendering. On lower-powered devices or when running multiple indicators simultaneously, users may experience lag. Use the performance optimization settings (reduce visual complexity, increase phase sample rate, disable unused oscillators) to improve responsiveness.
This system is most effective when used as one component within a broader trading methodology that includes sound risk management, multi-timeframe analysis, market context awareness, and disciplined execution. It is a tool for regime detection and signal confirmation, not a substitute for comprehensive trade planning.
Technical Notes
Calculation Timing : All signal logic (ignition, collapse) is evaluated using bar-close values. The barstate.isconfirmed or implicit bar-close behavior ensures signals do not repaint. Visual components (tables, plots) render on every tick for real-time feedback but do not affect signal generation.
Phase Wrapping : Phase angles are calculated in the range -180° to +180° using atan2. Angular distance calculations account for wrapping (e.g., the distance between +170° and -170° is 20°, not 340°). This ensures phase-lock detection works correctly across the ±180° boundary.
Array Management : The indicator uses fixed-size arrays for oscillator phases, amplitudes, and the entanglement matrix. The maximum number of oscillators is 8. If fewer oscillators are enabled, array sizes shrink accordingly (only active oscillators are processed).
Matrix Indexing : The entanglement matrix is stored as a flat array with size N×N, where N is the number of active oscillators. Index mapping: index(row, col) = row × N + col. Symmetric pairs (i,j) and (j,i) are stored identically.
Normalization Stability : Oscillators are normalized to using fixed reference levels (e.g., RSI overbought/oversold at 70/30). For unbounded oscillators (MACD, ROC, TSI), statistical normalization (division by rolling standard deviation) is used, with clamping to prevent extreme outliers from distorting phase calculations.
Smoothing and Lag : The CI smoothing window (SMA) introduces lag proportional to the window size. This is intentional—it filters out single-bar noise spikes in coherence. Users requiring faster reaction can reduce the smoothing window to 1-2 bars, at the cost of increased sensitivity to noise.
Complex Number Representation : Pine Script does not have native complex number types. Complex arithmetic is implemented using separate real and imaginary accumulators (sum_cos, sum_sin) and manual calculation of magnitude (sqrt(real² + imag²)) and argument (atan2(imag, real)).
Lookback Limits : The indicator respects Pine Script's maximum lookback constraints. Historical phase and amplitude values are accessed using the operator, with lookback limited to the chart's available bar history (max_bars_back=5000 declared).
Visual Rendering Performance : Tables (orbit plot, heat map, web, dashboard) are conditionally deleted and recreated on each update using table.delete() and table.new(). This prevents memory leaks but incurs redraw overhead. Rendering is restricted to barstate.islast (last bar) to minimize computational load—historical bars do not render visuals.
Alert Condition Triggers : alertcondition() functions evaluate on bar close when their boolean conditions transition from false to true. Alerts do not fire repeatedly while a condition remains true (e.g., CI stays above threshold for 10 bars fires only once on the initial cross).
Color Gradient Functions : The phaseColor() function maps phase angles to RGB hues using sine waves offset by 120° (red, green, blue channels). This creates a continuous spectrum where -180° to +180° spans the full color wheel. The amplitudeColor() function maps amplitude to grayscale intensity. The coherenceColor() function uses cos(phase) to map contribution to CI (positive = green, negative = red).
No External Data Requests : QRFM operates entirely on the chart's symbol and timeframe. It does not use request.security() or access external data sources. All calculations are self-contained, avoiding lookahead bias from higher-timeframe requests.
Deterministic Behavior : Given identical input parameters and price data, QRFM produces identical outputs. There are no random elements, probabilistic sampling, or time-of-day dependencies.
— Dskyz, Engineering precision. Trading coherence.
ATR Money Line Bands V2The "ATR Money Line Bands V2" is a clever TradingView overlay designed for trend identification with volatility-aware bands, evolving from basic ATR envelopes.
Reasoning Behind Construction: The core idea is to blend a smoothed trend line with dynamic volatility bands for reliable signals in varying markets. The "Money Line" uses linear regression (ta.linreg) on closes over a length (default 16) instead of a moving average, as it fits data via least-squares for a cleaner, forward-projected trend without lag artifacts. ATR (default 12-period) powers the bands because it measures true range volatility better than std dev in gappy assets like crypto/stocks—bands offset from the Money Line by ATR * multiplier (default 1.5). A dynamic multiplier (boosts by ~33% on spikes > prior ATR * 1.3) prevents tight bands from false breakouts during surges. Trend detection checks slope against an ATR-scaled tolerance (default 0.15) to ignore noise, labeling bull/bear/neutral—avoiding whipsaws in flats.
Properties: It's an overlay with a colored Money Line (green bull, red bear, yellow neutral) and invisible bands (toggle to show gray lines) filled semi-transparently matching trend for visual pop. Dynamic adaptation makes bands widen/contract intelligently. An info table (positionable, e.g., top_right) displays real-time values: Money Line, bands, ATR, trend—great for quick scans. Limits history (2000 bars) and labels (500) for efficiency.
Tips for Usage: Apply to any timeframe/asset; defaults suit medium-term (e.g., daily stocks). Watch color flips: green for longs (enter on pullbacks to lower band), red for shorts (vice versa), yellow to sit out. Use bands as S/R—breakouts signal momentum, squeezes impending vol. Tweak length for sensitivity (shorter for intraday), multiplier for width (higher for trends), tolerance for fewer neutrals. Pair with volume/RSI for confirmation; backtest to optimize. In choppy markets, disable dynamic mult to avoid over-expansion. Overall, it's adaptive and visual—helps trend-follow without overcomplicating.
Thematic Portfolio: Quantum Computing & Core TechThis indicator tracks the aggregated performance of a curated thematic portfolio representing the Quantum Computing & Core Technology sector.
It combines leading equities and ETFs with predefined weights to reflect a diversified exposure across quantum hardware, AI infrastructure, and semiconductor backbones.
Composition:
Stocks: Rigetti (RGTI), IonQ (IONQ), D-Wave (QBTS), Palantir (PLTR), Intel (INTC), Arqit (ARQQ)
ETFs: BUG, QTUM, SOXX, IHAK
Methodology:
Each component’s normalized performance is weighted according to its strategic importance within the theme (R&D intensity, infrastructure leverage, and hardware dependence). The indicator dynamically aggregates the weighted series to visualize the cumulative return of the quantum computing ecosystem versus traditional benchmarks.
Intended use:
Compare thematic returns vs. S&P 500 or NASDAQ
Identify macro inflection points in the quantum tech narrative
Backtest thematic exposure strategies or structure twin-win / delta-one certificates
Note: This script is for analytical and educational purposes only and does not constitute financial advice.
VolumeAnlaysis### Volume Analysis (VA) Indicator
**Overview**
The Volume Analysis (VA) indicator is a dynamic overlay tool designed for traders seeking to identify high-volume breakouts, retests, and multi-timeframe volume-driven price cycles. By combining volume spikes with price action and support/resistance boxes, it highlights potential trend continuations, reversals, and cycle shifts. Ideal for intraday and swing trading on stocks, forex, or crypto, it uses a Fibonacci-inspired 1.618 multiplier to detect significant volume surges, then maps them to visual boxes and key levels for actionable insights.
This indicator draws from volume profile concepts but focuses on **breakout confirmation** and **cycle momentum**, helping you spot when "smart money" volume aligns with price extremes. It's particularly useful in volatile markets where volume precedes price moves.
**How It Works**
1. **Volume Break Detection**:
- Identifies a "Volume Break" when the current bar's volume exceeds 1.618x the highest volume from the prior 5 bars. This signals unusual activity, often preceding breakouts.
- A "Volume Retest" triggers exactly 3 bars after a break if volume has been falling steadily over those 3 bars—indicating a pullback for re-accumulation/distribution.
2. **Visual Annotations**:
- **Labels**: Green/red/yellow labels mark Volume Breaks and Retests, positioned above/below the bar based on candle direction for clarity.
- **Demand/Supply Boxes**:
- Blue semi-transparent boxes form around Retest bars, extending rightward to act as dynamic support/resistance.
- Green (bullish) or red (bearish) boxes draw from Volume Breaks, based on the original candle's open/close, highlighting potential zones for continuation.
- Limited to 5 boxes max to avoid chart clutter; older boxes fade as new ones form.
3. **Box Interaction Signals**:
- When price enters a box:
- **Reversal Hints**: Maroon (bearish rejection) or lime (bullish rejection) labels on closes against the trend with opening price momentum.
- **Breakout Arrows**: Up/down arrows on crossovers/crossunders of box tops/bottoms from Retest boxes.
- Scans all active boxes for interactions, prioritizing recent volume events.
4. **Multi-Timeframe Volume Cycles**:
- Aggregates the "Volume Break Max" level (a proxy for key price extremes tied to volume spikes) across timeframes: 1min, 5min, 10min, 30min, and 65min (using `request.security`).
- Computes **MaxVolBreak** (highest extreme) and **MinVolBreak** (lowest extreme) for trend-following levels.
- Tracks **Percent Volume Greater/Less Than Close**: Sums volumes from TFs where price is below/above these levels, creating a momentum ratio.
- **CrossClose**: Plots the prior close where this ratio crosses (gray line), signaling cycle shifts—bullish below MinVolBreak, bearish above MaxVolBreak.
- **Fills**: Red fill above CrossClose/MaxVolBreak (bearish cycle); green below CrossClose/MinVolBreak (bullish cycle).
5. **Plots**:
- Black lines for MaxVolBreak (⏫) and MinVolBreak (⏬).
- Gray 🔄 for CrossClose.
- Colors dynamically adjust (green/red) based on close relative to levels.
**Key Features**
- **Trend vs. Reversal Modes**: Toggle alerts for trend-following breaks (crosses of Max/MinVolBreak) or reversal signals (crosses of CrossClose).
- **Multi-TF Fusion**: Optionally include the chart's native timeframe in Max/Min calculations for finer tuning.
- **Box Management**: Auto-prunes to 5 boxes; focuses on retest/break alignments for "inside bar" logic.
- **Momentum Filters**: Uses rising/falling opens and crossovers for label precision, reducing noise.
- **Customizable**: Simple inputs for alert visibility and timeframe inclusion.
**Settings**
| Input | Default | Description |
|-------|---------|-------------|
| Show Volume Reversal Breaks | False | Enables alerts/labels for CrossClose crosses (cycle reversals). |
| Show Trend Following Breaks | True | Enables alerts for Max/MinVolBreak crosses (trend signals). |
| Use Current Time | False | Includes chart's native TF in multi-TF Max/Min calculations. |
**Alerts**
- **Reversal Alerts** (if enabled): "Volume Reverse Bullish/Bearish Break of " on close crosses of CrossClose.
- **Trend Alerts** (if enabled): "Trend Volume Bullish/Bearish Signal" on close crosses of Max/MinVolBreak; plus notes if prior low/high aligns with levels.
- All alerts include ticker and level value for easy scanning. Use `alert.freq_once_per_bar` to avoid spam.
**Trading Ideas**
- **Bullish Entry**: Green box formation + price holding MinVolBreak + upward arrow on retest box. Target next resistance.
- **Bearish Entry**: Red box + close above MaxVolBreak + red fill activation. Stop below recent low.
- **Cycle Trading**: Watch CrossClose crosses for regime shifts—fade extremes in overextended cycles.
- **Best Timeframes**: 5-30min for intraday; combine with daily for swings. Works best on liquid assets with reliable volume data.
**Limitations & Notes**
- Relies on accurate volume data (e.g., stocks/forex); less effective on low-volume or synthetic instruments.
- Boxes extend rightward but don't auto-delete—monitor for clutter on long histories (max_bars_back=500).
- Some logic (e.g., exact 3-bar retest) is rigid; backtest for your market.
- Open-source under MPL 2.0—fork and tweak as needed!
For questions or enhancements, drop a comment below. Happy trading! 🚀
BB LONG 2BX & FVB StrategyThis Strategy is optimized for the 2h timeframe. Happy Charting and you're welcome!
**BB LONG 2BX & FVB Strategy – Simple Text Guide**
---
### **What It Does**
A **long-only trading strategy** that:
- Enters on **strong upward momentum**
- Adds a second position when the trend gets stronger
- Takes profits in parts at **smart price levels**
- Exits fully if the trend weakens or reverses
---
### **Main Tools Used**
| Tool | Simple Meaning |
|------|----------------|
| **B-Xtrender (Oscillator)** | Measures speed of price move. Above 0 = bullish, below 0 = bearish |
| **Weekly & Monthly Timeframes** | Checks if higher timeframes agree with the trade |
| **Red ATR Line** | A moving stop-loss that follows price up |
| **Fair Value Bands (1x, 2x, 3x)** | Profit targets that adjust to market volatility |
---
### **When It Enters a Trade (Long)**
**First Entry:**
- Weekly momentum is **rising**
- Monthly momentum is **positive or increasing**
- No current position
**Second Entry (Pyramiding):**
- Already in trade
- Price breaks **above the Red ATR line** → add same size again
(Max 2 total entries)
---
### **When It Takes Profit (Scaling Out)**
| Level | Action |
|-------|--------|
| **1x Band** | Sell **50%** when price pulls back from this level |
| **2x Band** | Sell **50%** when price pulls back from this level |
| **3x Band** | **Exit everything** when price pulls back from this level |
> You can hit 1x and 2x **multiple times** – it will keep taking 50% each time
---
### **When It Exits Fully (Closes Everything)**
1. Price **closes below Red ATR line**
2. Weekly momentum shows **2 red bars in a row, both falling**
3. Weekly momentum **crosses below zero** AND price is below Red ATR
4. Weekly momentum **drops sharply** (more than 25 points in one bar)
> After full exit, it **won’t re-enter** unless price comes back below 2x band
---
### **Alerts You Get**
Every time price **touches** a profit band, you get an alert:
- “Price touched 1x band from below”
- “Price touched 1x band from above”
- Same for **2x** and **3x**
> One alert per touch, per bar
---
### **On the Chart – What You See**
- **Histogram bars (weekly momentum)**
Lime = up, Red = down
**Yellow highlight** = warning (exit soon)
- **Red broken line** = stop-loss level
- **Blue line** = fair middle price
- **Orange, Purple, Pink lines** = 1x, 2x, 3x profit targets
---
### **Best Used On**
- Daily or 4-hour charts
- Strong trending assets (like Bitcoin, Tesla, S&P 500)
---
### **Quick Rules Summary**
| Do This | When |
|--------|------|
| **Enter** | Weekly up + monthly support |
| **Add more** | Price breaks above Red line |
| **Take 50% profit** | Price pulls back from 1x or 2x |
| **Exit all** | Red line break, weak momentum, or 3x hit |
---
**Simple Idea:**
**Ride strong trends, add when confirmed, take profits in chunks, cut losses fast.**
Relative Valuation OscillatorThis is a Relative Valuation Oscillator (RVO) this is attempt of replication OTC Valuation - a sophisticated multi-asset comparison indicator designed to measure whether the current asset is overvalued or undervalued relative to up to three reference assets.
Overview
The RVO compares the current chart's asset against reference assets (default: 30-Year Treasury Bonds, Gold, and US Dollar Index) to determine relative strength and valuation extremes. It outputs normalized oscillator values ranging from -100 (undervalued) to +100 (overvalued).
Key Features
Multiple Calculation Methods
The indicator offers 5 different calculation approaches:
Simple Ratio - Normalized ratio deviation from average
Percentage Difference - Percentage change comparison
Ratio Z-Score - Standard deviation-based comparison
Rate of Change Comparison - Momentum differential analysis (default)
Normalized Ratio - Min-max normalized ratio
Configurable Reference Assets
Asset 1: Default ZB (30-Year Treasury Bond Futures) - tracks interest rate sensitivity
Asset 2: Default GC (Gold Futures) - tracks safe-haven and inflation dynamics
Asset 3: Default DXY (US Dollar Index) - tracks currency strength
Each asset can be enabled/disabled independently
Fully customizable symbols
Visual Components
Multiple oscillator lines - One for each active reference asset (color-coded)
Average line - Combined signal from all active assets
Overbought/Oversold zones - Configurable threshold levels (default: ±80)
Zero line - Neutral valuation reference
Background coloring - Visual zones for extreme conditions
Signal line - Optional smoothed average
Entry markers - Long/short signals at key reversals
Signal Generation
Crossover alerts - When crossing overbought/oversold levels
Entry signals - Reversals from extreme zones
Divergence detection - Bullish/bearish divergences between price and oscillator
Zero-line crosses - Trend strength changes
Customization Options
Lookback period (10-500): Controls statistical calculation window
Normalization period (50-1000): Determines scaling sensitivity
Smoothing toggle: Optional EMA/SMA smoothing with adjustable period
Visual customization: Colors, levels, and display options
Information Table
Real-time dashboard showing:
Average oscillator value
Current status (Overvalued/Undervalued/Neutral)
Current asset price
Individual values for each active reference asset
Use Cases
Mean reversion trading - Identify extreme relative valuations for reversal trades
Sector rotation - Compare assets within similar categories
Hedging strategies - Understand correlation dynamics
Multi-asset analysis - Simultaneously compare against bonds, commodities, and currencies
Divergence trading - Spot price/oscillator divergences
Trading Strategy Applications
Long signals: When oscillator crosses above oversold level (asset recovering from undervaluation)
Short signals: When oscillator crosses below overbought level (asset declining from overvaluation)
Confirmation: Use multiple reference assets for stronger signals
Risk management: Avoid trading when all assets show neutral readings
This indicator is particularly useful for traders who want to incorporate inter-market analysis and relative strength concepts into their trading decisions, especially in OTC (Over-The-Counter) and futures markets.
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.
Trading Lot & Margin Calculator
# 💹 Trading Lot & Margin Calculator - Professional Risk Management Tool
## 🎯 Overview
A comprehensive, all-in-one calculator dashboard that helps traders determine optimal position sizes, calculate margin requirements, and manage risk effectively across multiple asset classes. This indicator displays directly on your chart as a customizable table, providing real-time calculations based on current market prices.
## ✨ Key Features
### 📊 Three Powerful Calculation Modes:
**1. Calculate Lot Size (Risk-Based Position Sizing)**
- Input your risk percentage and stop loss in pips
- Automatically calculates the optimal lot size for your risk tolerance
- Respects margin limitations (configurable margin % cap)
- Ensures positions don't exceed minimum lot size (0.01)
- Perfect for risk management and proper position sizing
**2. Calculate Margin Cost**
- Input desired lot size
- See exactly how much margin is required
- Shows percentage of deposit used
- Displays free margin remaining
- Warns when insufficient funds
**3. Margin to Lots**
- Specify a fixed margin amount you want to use
- Calculator shows how many lots/contracts you can buy
- Ideal for traders with fixed margin budgets
## 🤖 Auto-Detection of Instruments
The calculator **automatically detects** what you're trading and adjusts calculations accordingly:
### ✅ Fully Supported:
- **💱 Forex Pairs** - All majors, minors, exotics (EURUSD, GBPJPY, etc.)
- Standard lot: 100,000 units
- JPY pairs: 0.01 pip size, others: 0.0001
- **🛢️ Commodities** - Gold, Silver, Oil
- XAUUSD (Gold): 100 oz per lot
- XAGUSD (Silver): 5,000 oz per lot
- Oil (WTI/Brent): 1,000 barrels per lot
- **📈 Indices** - US500, NAS100, US30, DAX, etc.
- Correct contract sizes per point
- **📊 Stocks** - All individual stocks
- 1 lot = 1 share
- Direct share calculations
### ⚠️ Known Limitation:
- **₿ Crypto calculations may not work properly** on all crypto pairs. Use manual contract size if needed.
## 📋 Dashboard Information Displayed:
- 🎯 Optimal/Requested Lot Size
- 💰 Margin Required
- 📊 Margin % of Deposit
- 💵 Free Margin Remaining
- 💎 Position Value
- 📈 Pip/Point Value
- ⚠️ Safety Warnings (insufficient funds, high risk, etc.)
- 🔍 Detected Instrument Type
- 📦 Contract Size
## ⚙️ Customizable Settings:
**Account Settings:**
- Account Deposit
- Leverage (1:1 to 1:1000)
- Max Margin % of Deposit (default 5% for safety)
**Risk Management:**
- Risk Percentage (for lot size calculation)
- Stop Loss in Pips
- Lot Amount (for margin cost calculation)
- Margin to Use (for margin-to-lots calculation)
**Display Options:**
- Show/Hide Dashboard
- Position: Top/Middle/Bottom, Left/Right
- Auto-detect instrument ON/OFF
- Manual contract size override
## 🎨 Professional Design
- Clean, modern table interface
- Color-coded warnings (red = danger, yellow = caution, green = safe)
- Large, readable text
- Minimal screen space usage
- Non-intrusive overlay
## 💡 Use Cases:
1. **Day Traders** - Quick position sizing based on account risk
2. **Swing Traders** - Calculate optimal positions for longer-term setups
3. **Risk Managers** - Ensure positions stay within margin limits
4. **Beginners** - Learn proper position sizing and risk management
5. **Multi-Asset Traders** - Seamlessly switch between forex, commodities, indices, and stocks
## ⚠️ Important Notes:
- ✅ Works on all timeframes
- ✅ Updates in real-time with price changes
- ✅ Minimum lot size enforced (0.01)
- ✅ Margin calculations use current chart price
- ⚠️ **Crypto calculations may be inaccurate** - verify with your broker
- 📌 Always verify calculations with your broker's specifications
- 📌 Contract sizes may vary by broker
## 🚀 How to Use:
1. Add indicator to any chart
2. Click settings ⚙️ icon
3. Enter your account details (deposit, leverage)
4. Choose calculation mode
5. Input your parameters
6. View optimal lot size and margin requirements on dashboard
## 📈 Perfect For:
- Forex traders managing multiple currency pairs
- Commodity traders (Gold, Silver, Oil)
- Index traders (S&P 500, NASDAQ, etc.)
- Stock traders
- Anyone who wants professional risk management
## 🛡️ Risk Management Features:
- Configurable margin % cap prevents over-leveraging
- Risk-based position sizing protects your account
- Warnings for high risk, insufficient funds, margin limitations
- Prevents positions below minimum lot size
---
**Trade smarter, not harder. Calculate before you trade!** 📊💪
---
## Version Notes:
- Pine Script v6
- Overlay mode for chart display
- No external dependencies
- Lightweight and fast
**Disclaimer:** This calculator is for educational and informational purposes only. Always verify calculations with your broker and trade at your own risk. Past performance does not guarantee future results.
---
LANZ Origins🔷 LANZ Origins – Multi-Framework Liquidity, Structure & Risk Management Overlay
LANZ Origins is an advanced multi-framework visualization toolkit that unifies key institutional concepts into one efficient interface. Designed for professional traders, it merges session mapping, liquidity analysis, imbalance detection, multi-account risk control, and higher-timeframe candle tracing — all in a single overlay.
🧩 Core Components
🈵 Asian Range Liquidity
Automatically detects and projects the Asian session range (19:00–02:00 NY) with an optional mid-price line (50 %). This provides visual context for intraday liquidity and manipulation zones commonly referenced in ICT-style analysis.
📊 Imbalance Detector
Highlights Fair Value Gaps (FVG), Opening Gaps (OG), and Volume Imbalances (VI) directly on-chart, using separate color schemes for bullish and bearish inefficiencies. Each element can be customized by width, ATR filter, and extension length.
🕯️ Higher-Timeframe Candles (ICT Style)
Displays multi-timeframe candles (HTF1–HTF6) simultaneously — e.g., 5 m, 30 m, 1 h, 4 h, 1 D, 1 W — each rendered with independent wick, border, and fill settings. Includes remaining-time counters, timeframe labels, and optional imbalance shading between bodies.
📈 Market Structure (ZigZag 30 m)
Replicates 30-minute swing structure to all active timeframes, producing dynamic pivots with live extension. Ideal for contextualizing BOS/CHoCH events across multiple scales.
💸 Multi-Account Lot Size Panel
Calculates position size for up to five accounts simultaneously, using your defined capital, risk %, and fixed SL distance (in pips). Results appear in a clean table at the bottom-right corner of the chart.
🎨 Session Visualization
Colored backgrounds mark key trading phases:
🟢 Day division
🔴 No-action zone
🔵 Kill-zone
🟡 Hold session
⚙️ Customization & Performance
Every module can be toggled individually, with full color, opacity, and style control. The script is optimized for overlay use and supports up to 500 boxes, lines, and labels with efficient resource handling.
🧠 Best Use Case
LANZ Origins is ideal for traders who follow:
Smart Money Concepts / ICT methodology
Liquidity & Imbalance-based trading
Multi-timeframe confluence setups
Risk-based position sizing workflows
Use it to observe how price interacts with liquidity pools, higher-timeframe candles, and imbalances within key sessions — while monitoring lot size risk in real time.
📌 Recommended Setup
Timeframes: 30m - 5m – 3m
Pairs: FX
Session Timezone: New York (EST/EDT)
Combine with: LANZ Strategy series for execution and journaling
💬 Note
This indicator does not generate buy/sell signals. It’s a visual and analytical tool built to support your own decision-making process.
Economic Cycle Signal (USA)📊 Economic Cycle Signal (USA)
This indicator overlays both the U.S. Federal Reserve Funds Rate (Fed Funds) and the U.S. Inflation Rate YoY directly onto your stock market chart (e.g., S&P 500). It visually connects monetary policy and inflation dynamics with equity market performance, helping traders and analysts understand how macroeconomic shifts impact risk assets.
🔹 Key Features
• Plots the monthly U.S. Fed Funds Rate alongside your chart.
• Overlays the U.S. Inflation Rate YoY, offering a direct and realistic view of inflation pressure instead of CPI.
• Shades the background to reflect different economic cycle phases (recovery, recession, expansion, late cycle).
• Highlights how the stock market reacts during shifting monetary and inflationary conditions.
• Provides a clear traffic-light style signal for quick macro interpretation.
• Now includes dynamic inflation color logic based on the Fed’s 2% target and 5% threshold (explained below).
🔹 Inflation Line Color Logic (New)
The inflation line now changes color dynamically to show whether inflation is within or outside the Federal Reserve’s comfort zone, and whether it’s rising or falling:
Inflation Condition Interpretation Line Color
Inflation > 5% and Rising Inflation overheating (well above target) 🔴 Red
Inflation > 5% and Falling Cooling off from high levels 💚 Lime
Inflation < 5% and Falling Disinflation / stable price environment 🟢 Green
Inflation < 5% and Rising Early inflation rebound 🟡 Yellow
This color-coded logic mirrors the interest rate phase colors, giving traders an instant visual cue about inflationary pressure and possible policy turning points.
🔹 How Traders & Analysts Can Use It
• Visualize the interaction between U.S. monetary policy and inflation cycles in real time.
• Identify historically supportive phases when low or easing rates follow moderate inflation.
• Detect tightening cycles when inflation spikes first and the Fed reacts, signaling potential equity headwinds.
• Use as a macro compass to anticipate inflation pressure, policy changes, and market regime shifts.
• Combine with technical analysis, fundamentals, or leading indicators for deeper macro insights.
🔹 Color Legend (Economic Phases)
🟩 Light Green → Recovery (Early Cycle)
• Rates: low or falling
• Inflation: low/stable
🟩 Green → Recession (Down Cycle)
• Rates: cut aggressively
• Inflation: falling
🟨 Yellow → Expansion (Mid Cycle)
• Rates: rising gradually
• Inflation: moderate
🟥 Red → Overheating (Late Cycle)
• Rates: high / rising fast
• Inflation: high
🔹 Inflation Context
• Inflation typically leads the policy rate cycle, offering early insight into future Fed actions.
• The U.S. Inflation Rate YoY provides a direct measure of consumer price changes compared to the same month last year — a clearer gauge of inflation pressure than CPI.
• The new color logic helps visualize whether inflation is accelerating or cooling, relative to the Fed’s 2% target and 5% upper threshold.
• This dual-overlay makes it easy to interpret the cause (inflation) and effect (interest rate policy) in one synchronized chart.
⚠️ Disclaimer
This script is for educational and informational purposes only. It does not provide financial advice or trading signals. Always combine it with your own research, proper risk management, and professional judgment.
Pivot Regime Anchored VWAP [CHE] Pivot Regime Anchored VWAP — Detects body-based pivot regimes to classify swing highs and lows, anchoring volume-weighted average price lines directly at higher highs and lower lows for adaptive reference levels.
Summary
This indicator identifies shifts between top and bottom regimes through breakouts in candle body highs and lows, labeling swing points as higher highs, lower highs, lower lows, or higher lows. It then draws anchored volume-weighted average price lines starting from the most recent higher high and lower low, providing dynamic support and resistance that evolve with volume flow. These anchored lines differ from standard volume-weighted averages by resetting only at confirmed swing extremes, reducing noise in ranging markets while highlighting momentum shifts in trends.
Motivation: Why this design?
Traders often struggle with static reference lines that fail to adapt to changing market structures, leading to false breaks in volatile conditions or missed continuations in trends. By anchoring volume-weighted average price calculations to body pivot regimes—specifically at higher highs for resistance and lower lows for support—this design creates reference levels tied directly to price structure extremes. This approach addresses the problem of generic moving averages lagging behind swing confirmations, offering a more context-aware tool for intraday or swing trading.
What’s different vs. standard approaches?
- Baseline reference: Traditional volume-weighted average price indicators compute a running total from session start or fixed periods, often ignoring price structure.
- Architecture differences:
- Regime detection via body breakout logic switches between high and low focus dynamically.
- Anchoring limited to confirmed higher highs and lower lows, with historical recalculation for accurate line drawing.
- Polyline rendering rebuilds only on the last bar to manage performance.
- Practical effect: Charts show fewer, more meaningful lines that start at swing points, making it easier to spot confluences with structure breaks rather than cluttered overlays from continuous calculations.
How it works (technical)
The indicator first calculates the maximum and minimum of each candle's open and close to define body highs and lows. It then scans a lookback window for the highest body high and lowest body low. A top regime triggers when the body high from the lookback period exceeds the window's highest, and a bottom regime when the body low falls below the window's lowest. These regime shifts confirm pivots only when crossing from one state to the other.
For top pivots, it compares the new body high against the previous swing high: if greater, it marks a higher high and anchors a new line; otherwise, a lower high. The same logic applies inversely for bottom pivots. Anchored lines use cumulative price-volume products and volumes from the anchor bar onward, subtracting prior cumulatives to isolate the segment. On pivot confirmation, it loops backward from the current bar to the anchor, computing and storing points for the line. New points append as bars advance, ensuring the line reflects ongoing volume weighting.
Initialization uses persistent variables to track the last swing values and anchor bars, starting with neutral states. Data flows from regime detection to pivot classification, then to anchoring and point accumulation, with lines rendered globally on the final bar.
Parameter Guide
Pivot Length — Controls the lookback window for detecting body breakouts, influencing pivot frequency and sensitivity to recent action. Shorter values catch more pivots in choppy conditions; longer smooths for major swings. Default: 30 (bars). Trade-offs/Tips: Min 1; for intraday, try 10–20 to reduce lag but watch for noise; on daily, 50+ for stability.
Show Pivot Labels — Toggles display of text markers at swing points, aiding quick identification of higher highs, lower highs, lower lows, or higher lows. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to declutter; useful for backtesting structure.
HH Color — Sets the line and label color for higher high anchored lines, distinguishing resistance levels. Default: Red (solid). Trade-offs/Tips: Choose contrasting hues for dark/light themes; pair with opacity for fills if added later.
LL Color — Sets the line and label color for lower low anchored lines, distinguishing support levels. Default: Lime (solid). Trade-offs/Tips: As above; green shades work well for bullish contexts without overpowering candles.
Reading & Interpretation
Higher high labels and red lines indicate potential resistance zones where volume weighting begins at a new swing top, suggesting sellers may defend prior highs. Lower low labels and lime lines mark support from a fresh swing bottom, with the line's slope reflecting buyer commitment via volume. Lower highs or higher lows appear as labels without new anchors, signaling possible range-bound action. Line proximity to price shows overextension; crosses may hint at regime shifts, but confirm with volume spikes.
Practical Workflows & Combinations
- Trend following: Enter longs above a rising lower low anchored line after higher low confirmation; filter with rising higher highs for uptrends. Use line breaks as trailing stops.
- Exits/Stops: In downtrends, exit shorts below a higher high line; set aggressive stops above it for scalps, conservative below for swings. Pair with momentum oscillators for divergence.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; on crypto 15M, shorten length to 15. Scale colors for dark themes; combine with higher timeframe anchors for confluence.
Behavior, Constraints & Performance
Closed-bar logic ensures pivots confirm after the lookback period, with no repainting on historical bars—live bars may adjust until regime shift. No higher timeframe calls, so minimal repaint risk beyond standard delays. Resources include a 2000-bar history limit, label/polyline caps at 200/50, and loops for historical point filling (up to current bar count from anchor, typically under 500 iterations). Known limits: In extreme gaps or low-volume periods, anchors may skew; lines absent until first pivots.
Sensible Defaults & Quick Tuning
Start with the 30-bar length for balanced pivot detection across most assets. For too-frequent pivots in ranges, increase to 50 for fewer signals. If lines lag in trends, reduce to 20 and enable labels for visual cues. In low-volatility assets, widen color contrasts; test on 100-bar history to verify stability.
What this indicator is—and isn’t
This is a structure-aware visualization layer for anchoring volume-weighted references at swing extremes, enhancing manual analysis of regimes and levels. It is not a standalone signal generator or predictive model—always integrate with broader context like order flow or news. Use alongside risk management and position sizing, not as isolated buy/sell triggers.
Many thanks to LuxAlgo for the original script "McDonald's Pattern ". The implementation for body pivots instead of wicks uses a = max(open, close), b = min(open, close) and then highest(a, length) / lowest(b, length). This filters noise from the wicks and detects breakouts over/under bodies. Unusual and targeted, super innovative.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
HermesHERMES STRATEGY - TRADINGVIEW DESCRIPTION
OVERVIEW
Hermes is an adaptive trend-following strategy that uses dual ALMA (Arnaud Legoux Moving Average) filters to identify high-quality entry and exit points. It's designed for swing and position traders who want smooth, low-lag signals with minimal whipsaws.
Unlike traditional moving averages that operate on price, Hermes analyzes price returns (percentage changes) to create signals that work consistently across any asset class and price range.
HOW IT WORKS
DUAL ALMA SYSTEM
The strategy uses two ALMA lines applied to price returns:
• Fast ALMA (Blue Line): Short-term trend signal (default: 80 periods)
• Slow ALMA (Black Line): Long-term baseline trend (default: 250 periods)
ALMA is superior to simple or exponential moving averages because it provides:
• Smoother curves with less noise
• Significantly reduced lag
• Natural resistance to outliers and flash crashes
TRADING LOGIC
BUY SIGNAL:
• Fast ALMA crosses above Slow ALMA (bullish regime)
• Price makes new N-bar high (momentum confirmation)
• Optional: Price above 200 EMA (macro trend filter)
• Optional: ALMA lines sufficiently separated (strength filter)
SELL SIGNAL:
• Fast ALMA crosses below Slow ALMA (bearish regime)
• Optional: Price makes new N-bar low (momentum confirmation)
The strategy stays in position during the entire bullish regime, allowing you to ride trends for weeks or months.
VISUAL INDICATORS
LINES:
• Blue Line: Fast ALMA (short-term signal)
• Black Line: Slow ALMA (long-term baseline)
TRADE MARKERS:
• Green Triangle Up: Buy executed
• Red Triangle Down: Sell executed
• Orange "M": Buy blocked by momentum filter
• Purple "W": Buy blocked by weak crossover strength
KEY PARAMETERS
ALMA SETTINGS:
• Short Period (default: 30) - Fast signal responsiveness
• Long Period (default: 250) - Baseline stability
• ALMA Offset (default: 0.90) - Balance between lag and smoothness
• ALMA Sigma (default: 7.5) - Gaussian curve width
ENTRY/EXIT FILTERS:
• Buy Lookback (default: 7) - Bars for momentum confirmation (required)
• Sell Lookback (default: 0) - Exit momentum bars (0 = disabled for faster exits)
• Min Crossover Strength (default: 0.0) - Required ALMA separation (0 = disabled)
• Use Macro Filter (default: true) - Only enter above 200 EMA
BEST PRACTICES
RECOMMENDED ASSETS - Works well on:
• Cryptocurrencies (Bitcoin, Ethereum, etc.)
• Major indices (S&P 500, Nasdaq)
• Large-cap stocks
• Commodities (Gold, Oil)
RECOMMENDED TIMEFRAMES:
• Daily: Primary timeframe for swing trading
• 4-Hour: More active trading (increase trade frequency)
• Weekly: Long-term position trading
PARAMETER TUNING:
• More trades: Lower Short Period (60-80)
• Fewer trades: Raise Short Period (100-120)
• Faster exits: Set Sell Lookback = 0
• Safer entries: Enable Macro Filter (Use Macro Filter = true)
STRATEGY ADVANTAGES
1. Low Lag - ALMA provides faster signals than traditional moving averages
2. Smooth Signals - Minimal whipsaws compared to crossover strategies
3. Asset Agnostic - Same parameters work across different markets
4. Trend Capture - Stays positioned during entire bullish regimes
5. Risk Management - Multiple filters prevent poor entries
6. Visual Clarity - Easy to interpret regime and filter states
WHEN TO USE HERMES
BEST FOR:
• Trending markets (crypto bull runs, equity uptrends)
• Swing trading (hold days to weeks)
• Position trading (hold weeks to months)
• Clear trend identification
• Risk-managed exposure
NOT SUITABLE FOR:
• Ranging/sideways markets
• Scalping or day trading
• High-frequency trading
• Mean reversion strategies
RISK DISCLAIMER
This indicator is for educational purposes only. Past performance does not guarantee future results. Always use proper position sizing and risk management. Test thoroughly on historical data before live trading.
CREDITS
Inspired by Giovanni Santostasi's Power Law Volatility Indicator, generalized for universal application across all assets using adaptive ALMA filtering.
Strategy by Hermes Trading Systems
QUICK START
1. Add indicator to chart
2. Use on daily timeframe for best results
3. Look for green buy signals when blue line crosses above black line
4. Exit on red sell signals when blue line crosses below black line
5. Adjust parameters based on your trading style:
• Conservative: Enable Macro Filter, increase Buy Lookback to 10
• Aggressive: Disable Macro Filter, lower Short Period to 60
• Default settings work well for most assets
Luxy Adaptive MA Cloud - Trend Strength & Signal Tracker V2Luxy Adaptive MA Cloud - Professional Trend Strength & Signal Tracker
Next-generation moving average cloud indicator combining ultra-smooth gradient visualization with intelligent momentum detection. Built for traders who demand clarity, precision, and actionable insights.
═══════════════════════════════════════════════
WHAT MAKES THIS INDICATOR SPECIAL?
═══════════════════════════════════════════════
Unlike traditional MA indicators that show static lines, Luxy Adaptive MA Cloud creates a living, breathing visualization of market momentum. Here's what sets it apart:
Exponential Gradient Technology
This isn't just a simple fill between two lines. It's a professionally engineered gradient system with 26 precision layers using exponential density distribution. The result? An organic, cloud-like appearance where the center is dramatically darker (15% transparency - where crossovers and price action occur), while edges fade gracefully (75% transparency). Think of it as a visual "heat map" of trend strength.
Dynamic Momentum Intelligence
Most MA clouds only show structure (which MA is on top). This indicator shows momentum strength in real-time through four intelligent states:
- 🟢 Bright Green = Explosive bullish momentum (both MAs rising strongly)
- 🔵 Blue = Weakening bullish (structure intact, but momentum fading)
- 🟠 Orange = Caution zone (bearish structure forming, weak momentum)
- 🔴 Deep Red = Strong bearish momentum (both MAs falling)
The cloud literally tells you when trends are accelerating or losing steam.
Conditional Performance Architecture
Every calculation is optimized for speed. Disable a feature? It stops calculating entirely—not just hidden, but not computed . The 26-layer gradient only renders when enabled. Toggle signals off? Those crossover checks don't run. This makes it one of the most efficient cloud indicators available, even with its advanced visual system.
Zero Repaint Guarantee
All signals and momentum states are based on confirmed bar data only . What you see in historical data is exactly what you would have seen trading live. No lookahead bias. No repainting tricks. No signals that "magically" appear perfect in hindsight. If a signal shows in history, it would have triggered in real-time at that exact moment.
Educational by Design
Every single input includes comprehensive tooltips with:
- Clear explanations of what each parameter does
- Practical examples of when to use different settings
- Recommended configurations for scalping, day trading, and swing trading
- Real-world trading impact ("This affects entry timing" vs "This is visual only")
You're not just getting an indicator—you're learning how to use it effectively .
═══════════════════════════════════════════════
THE GRADIENT CLOUD - TECHNICAL DETAILS
═══════════════════════════════════════════════
Architecture:
26 precision layers for silk-smooth transitions
Exponential density curve - layers packed tightly near center (where crossovers happen), spread wider at edges
75%-15% transparency range - center is highly opaque (15%), edges fade gracefully (75%)
V-Gradient design - emphasizes the action zone between Fast and Medium MAs
The Four Momentum States:
🟢 GREEN - Strong Bullish
Fast MA above Medium MA
Both MAs rising with momentum > 0.02%
Action: Enter/hold LONG positions, strong uptrend confirmed
🔵 BLUE - Weak Bullish
Fast MA above Medium MA
Weak or flat momentum
Action: Caution - bullish structure but losing strength, consider trailing stops
🟠 ORANGE - Weak Bearish
Medium MA above Fast MA
Weak or flat momentum
Action: Warning - bearish structure developing, consider exits
🔴 RED - Strong Bearish
Medium MA above Fast MA
Both MAs falling with momentum < -0.02%
Action: Enter/hold SHORT positions, strong downtrend confirmed
Smooth Transitions: The momentum score is smoothed using an 8-bar EMA to eliminate noise and prevent whipsaws. You see the true trend , not every minor fluctuation.
═══════════════════════════════════════════════
FLEXIBLE MOVING AVERAGE SYSTEM
═══════════════════════════════════════════════
Three Customizable MAs:
Fast MA (default: EMA 10) - Reacts quickly to price changes, defines short-term momentum
Medium MA (default: EMA 20) - Balances responsiveness with stability, core trend reference
Slow MA (default: SMA 200, optional) - Long-term trend filter, major support/resistance
Six MA Types Available:
EMA - Exponential; faster response, ideal for momentum and day trading
SMA - Simple; smooth and stable, best for swing trading and trend following
WMA - Weighted; middle ground between EMA and SMA
VWMA - Volume-weighted; reflects market participation, useful for liquid markets
RMA - Wilder's smoothing; used in RSI/ADX, excellent for trend filters
HMA - Hull; extremely responsive with minimal lag, aggressive option
Recommended Settings by Trading Style:
Scalping (1m-5m):
Fast: EMA(5-8)
Medium: EMA(10-15)
Slow: Not needed or EMA(50)
Day Trading (5m-1h):
Fast: EMA(10-12)
Medium: EMA(20-21)
Slow: SMA(200) for bias
Swing Trading (4h-1D):
Fast: EMA(10-20)
Medium: EMA(34-50)
Slow: SMA(200)
Pro Tip: Start with Fast < Medium < Slow lengths. The gradient works best when there's clear separation between Fast and Medium MAs.
═══════════════════════════════════════════════
CROSSOVER SIGNALS - CLEAN & RELIABLE
═══════════════════════════════════════════════
Golden Cross ⬆ LONG Signal
Fast MA crosses above Medium MA
Classic bullish reversal or trend continuation signal
Most reliable when accompanied by GREEN cloud (strong momentum)
Death Cross ⬇ SHORT Signal
Fast MA crosses below Medium MA
Classic bearish reversal or trend continuation signal
Most reliable when accompanied by RED cloud (strong momentum)
Signal Intelligence:
Anti-spam filter - Minimum 5 bars between signals prevents noise
Clean labels - Placed precisely at crossover points
Alert-ready - Built-in ALERTS for automated trading systems
No repainting - Signals based on confirmed bars only
Signal Quality Assessment:
High-Quality Entry:
Golden Cross + GREEN cloud + Price above both MAs
= Strong bullish setup ✓
Low-Quality Entry (skip or wait):
Golden Cross + ORANGE cloud + Choppy price action
= Weak bullish setup, likely whipsaw ✗
═══════════════════════════════════════════════
REAL-TIME INFO PANEL
═══════════════════════════════════════════════
An at-a-glance dashboard showing:
Trend Strength Indicator:
Visual display of current momentum state
Color-coded header matching cloud color
Instant recognition of market bias
MA Distance Table:
Shows percentage distance of price from each enabled MA:
Green rows : Price ABOVE MA (bullish)
Red rows : Price BELOW MA (bearish)
Gray rows : Price AT MA (rare, decision point)
Distance Interpretation:
+2% to +5%: Healthy uptrend
+5% to +10%: Getting extended, caution
+10%+: Overextended, expect pullback
-2% to -5%: Testing support
-5% to -10%: Oversold zone
-10%+: Deep correction or downtrend
Customization:
4 corner positions
5 font sizes (Tiny to Huge)
Toggle visibility on/off
═══════════════════════════════════════════════
HOW TO USE - PRACTICAL TRADING GUIDE
═══════════════════════════════════════════════
STRATEGY 1: Trend Following
Identify trend : Wait for GREEN (bullish) or RED (bearish) cloud
Enter on signal : Golden Cross in GREEN cloud = LONG, Death Cross in RED cloud = SHORT
Hold position : While cloud maintains color
Exit signals :
• Cloud turns ORANGE/BLUE = momentum weakening, tighten stops
• Opposite crossover = close position
• Cloud turns opposite color = full reversal
STRATEGY 2: Pullback Entries
Confirm trend : GREEN cloud established (bullish bias)
Wait for pullback : Price touches or crosses below Fast MA
Enter when : Price rebounds back above Fast MA with cloud still GREEN
Stop loss : Below Medium MA or recent swing low
Target : Previous high or when cloud weakens
STRATEGY 3: Momentum Confirmation
Your setup triggers : (e.g., chart pattern, support/resistance)
Check cloud color :
• GREEN = proceed with LONG
• RED = proceed with SHORT
• BLUE/ORANGE = skip or reduce size
Use gradient as confluence : Not as primary signal, but as momentum filter
Risk Management Tips:
Never enter against the cloud color (don't LONG in RED cloud)
Reduce position size during BLUE/ORANGE (transition periods)
Place stops beyond Medium MA for swing trades
Use Slow MA (200) as final trend filter - don't SHORT above it in uptrends
═══════════════════════════════════════════════
PERFORMANCE & OPTIMIZATION
═══════════════════════════════════════════════
Tested On:
Crypto: BTC, ETH, major altcoins
Stocks: SPY, AAPL, TSLA, QQQ
Forex: EUR/USD, GBP/USD, USD/JPY
Indices: S&P 500, NASDAQ, DJI
═══════════════════════════════════════════════
TRANSPARENCY & RELIABILITY
═══════════════════════════════════════════════
Educational Focus:
Detailed tooltips on every input
Clear documentation of methodology
Practical examples in descriptions
Teaches you why , not just what
Open Logic:
Momentum calculation: (Fast slope + Medium slope) / 2
Smoothing: 8-bar EMA to reduce noise
Thresholds: ±0.02% for strong momentum classification
Everything is transparent and explainable
═══════════════════════════════════════════════
COMPLETE FEATURE LIST
═══════════════════════════════════════════════
Visual Components:
26-layer exponential gradient cloud
3 customizable moving average lines
Golden Cross / Death Cross labels
Real-time info panel with trend strength
MA distance table
Calculation Features:
6 MA types (EMA, SMA, WMA, VWMA, RMA, HMA)
Momentum-based cloud coloring
Smoothed trend strength scoring
Conditional performance optimization
Customization Options:
All MA lengths adjustable
All colors customizable (when gradient disabled)
Panel position (4 corners)
Font sizes (5 options)
Toggle any feature on/off
Signal Features:
Anti-spam filter (configurable gap)
Clean, non-overlapping labels
Built-in alert conditions
No repainting guarantee
═══════════════════════════════════════════════
IMPORTANT DISCLAIMERS
═══════════════════════════════════════════════
This indicator is for educational and informational purposes only
Not financial advice - always do your own research
Past performance does not guarantee future results
Use proper risk management - never risk more than you can afford to lose
Test on paper/demo accounts before using with real money
Combine with other analysis methods - no single indicator is perfect
Works best in trending markets; less effective in choppy/sideways conditions
Signals may perform differently in different timeframes and market conditions
The indicator uses historical data for MA calculations - allow sufficient lookback period
═══════════════════════════════════════════════
CREDITS & TECHNICAL INFO
═══════════════════════════════════════════════
Version: 2.0
Release: October 2025
Special Thanks:
TradingView community for feedback and testing
Pine Script documentation for technical reference
═══════════════════════════════════════════════
SUPPORT & UPDATES
═══════════════════════════════════════════════
Found a bug? Comment below with:
Ticker symbol
Timeframe
Screenshot if possible
Steps to reproduce
Feature requests? I'm always looking to improve! Share your ideas in the comments.
Questions? Check the tooltips first (hover over any input) - most answers are there. If still stuck, ask in comments.
═══════════════════════════════════════════════
Happy Trading!
Remember: The best indicator is the one you understand and use consistently. Take time to learn how the cloud behaves in different market conditions. Practice on paper before going live. Trade smart, manage risk, and may the trends be with you! 🚀






















