OPEN-SOURCE SCRIPT
Harmonic Frequency Visualizer [BackQuant]

Harmonic Frequency Visualizer [BackQuant]
Overview
Harmonic Frequency Visualizer is a cycle-analysis and cross-asset resonance tool that uses a simplified Discrete Fourier Transform (DFT) to measure how strongly specific cycle periods are present in price. It is not a “trend indicator” and it is not trying to predict direction by itself. Its job is to quantify rhythm: which repeating periods (in bars) are currently dominant, whether those cycles are expanding or contracting (phase direction), and whether multiple instruments are sharing the same dominant periods at the same time (resonance).
This indicator has two main output modes:
Spectrum

Spectrogram

On top of that, it produces a Dominant Cycle Oscillator derived from the dominant cycle’s phase, which gives a continuous cycle position metric (peak/trough style zones) without repainting.
This is designed for traders who want cycle context the same way they want volatility context: not as a magic signal, but as structure.
What “frequency” and “cycles” mean in trading terms
A cycle period (say 21 bars) means: “a repeating pattern that tends to complete one full oscillation every 21 bars.” If price contains such a pattern, the DFT will detect a strong correlation between price and a 21-bar sine/cosine wave.
Markets do not have perfectly stable periodic motion, but they often show:
Cycle tools are trying to measure those repeating components, and DFT is the standard mathematical way to do it.
Where DFT comes from (the core idea)
The Discrete Fourier Transform comes from Fourier analysis, a foundational signal processing concept:
Fourier’s idea: any sufficiently well-behaved signal can be expressed as a sum of sine and cosine waves at different frequencies, each with:
In continuous math you get the Fourier Transform. In sampled data (like candles) you use the Discrete Fourier Transform. It converts a time series (price over time) into a frequency description (strength of different cycles).
In markets:
Why sine and cosine, not just sine
A sine wave alone cannot represent every phase alignment cleanly. DFT uses both cosine and sine components because together they form an orthogonal basis that can represent any phase shift.
You can think of it like this:
Mathematically, a single frequency component can be written as:
But DFT estimates A and φ by separately accumulating cosine and sine projections.
How this script implements the DFT (and what it is actually measuring)
This is not a full-spectrum FFT across every frequency. It is a targeted DFT across a fixed set of cycle periods:
Tested periods
The script tests 8 predefined periods:
These are Fibonacci-like cycle candidates commonly used in cycle/market structure work. The point is not that Fibonacci is magic. The point is that these represent a reasonable spread from short to long rhythms without needing hundreds of frequencies (which would be heavy in Pine).
Normalization step (important)
Before computing the DFT, the script normalizes the series:
Why normalize:
So the spectrum is measuring “cyclical structure in standardized deviations,” not raw dollars.
Projection onto cosine and sine
For each tested period P:
Interpretation:
Window length detail
The script uses:
So even if lookback is 200, the internal DFT accumulation caps at 100 bars for performance stability. This is a deliberate trade: stable computation in Pine, while still letting you define normalization lookback and overall context.
Amplitude computation
Once sCos and sSin are computed:
This is the length of the vector (sCos, sSin). That vector length is the standard way to combine the orthogonal components into one strength metric.
Then it scales it into a 0–100 “display amplitude”:
So:
Important: amplitude here is not a probability, and it is not guaranteed “signal quality.” It is a standardized “how much of that cycle exists in the recent window” metric.
Phase computation
Phase is computed using atan2(sSin, sCos). That matters because:
Phase tells you where you are within the cycle:
Dominant cycle selection
The script chooses the dominant cycle as the period with the highest amplitude among the tested periods:
This dominant cycle is used for:
Spectrum View: what you see and how to read it
In Spectrum mode, the indicator draws a frequency snapshot for up to five instruments. Each instrument gets a spectrum line (or bars/area depending on style) plotted across the 8 periods on the x-axis, with amplitude (0–100) on the y-axis.
X-axis meaning
Each x position corresponds to a period (5 → 120 bars). You are not looking at “frequency in Hz.” You are looking at “period in bars,” which is more intuitive in trading.
Y-axis meaning
Amplitude is a scaled measure of how strongly that period is present in the recent normalized data. Higher means stronger.
Plot styles
Dominant peaks and phase direction labels
The script highlights dominant cycles per symbol (if enabled):
Phase direction logic:
This is not “price will rise now.” It is “the dominant cycle’s instantaneous phase suggests you are on the upward vs downward half of that oscillation.” In real markets, you use this as context, not as a standalone trade trigger.
It also draws small ▲/▼ markers on secondary peaks (amp > 15) to show phase direction of other meaningful cycles, giving you a richer picture than “one dominant period.”
Resonance Zones: cross-asset harmonic alignment
Resonance is where this tool becomes more than a single-chart curiosity.
What resonance means here
A resonance zone is flagged when at least 3 out of 5 instruments have strong amplitude at the same tested period. Mechanically:
When resonance is detected:
Interpretation:
This is especially useful when your instrument set includes:
Resonance is not automatically bullish or bearish. It is telling you “cycle length agreement,” which can help with timing models and contextual trade planning.
Spectrogram View: frequency over time
Spectrum mode is a snapshot. Spectrogram mode adds time evolution.
What a spectrogram is
A spectrogram is a 2D heatmap where:
This allows you to see:
How the script builds the spectrogram matrix
It maintains a matrix with:
Each bar:
So the spectrogram is always a rolling history of the chart symbol’s cycle amplitudes. It does not attempt to store five symbols (too heavy), it focuses on the active chart for time evolution.
Heat coloring
Amplitude values map to a custom gradient:
This makes dominant energy bands visually obvious. A stable bright band means persistent cycle dominance.
Dominant Cycle Oscillator: phase mapped to a 0–100 oscillator
The oscillator is derived from the dominant cycle phase (chart symbol):
Interpretation:
It also colors the oscillator by phase direction:
This gives you a clean timing reference:
It is not forecasting price. It is telling you the current phase position of the strongest detected cycle component.
Alerts and practical timing usage
Alerts are based on the oscillator:
In practice, you use these as “timing context” alerts, for example:
Again: cycle timing needs structure confirmation. The oscillator alone is not a trade system.
Multi-instrument design and non-repaint behavior
The indicator requests five external instruments via request.security. It uses:
This forces the data to be “previous confirmed close” so the spectral calculations do not repaint intra-bar. That matters because cycle measures can change drastically within a bar if you let them use live values.
So:
Key parameters and how they change behavior
Analysis Lookback
Affects normalization and the DFT window cap:
Because the inner DFT accumulation caps at 100 bars, very high lookback mostly affects normalization rather than the raw projection length.
Sensitivity
Scales displayed amplitude:
It is a display control, not a physics constant.
View Mode
Show Phase Direction
Adds ▲/▼ markers derived from sin(phase). Useful for quick cycle position intuition, but do not treat ▲ as “buy.”
Show Resonance Zones
Marks periods where many instruments share strong energy. Useful for macro rhythm alignment.
Highlight Dominant Cycles
Labels peaks. If you disable it, the chart becomes cleaner but less informative.
Spectrogram History
Controls how many columns are stored. Higher makes a longer heatmap but costs more drawing.
Limitations and what not to assume
This tool is honest DSP applied to market data, but market data is not a stationary sine wave generator. Key limitations:
This is why the indicator is best used as:
How to use it properly (workflows)
1) Cycle regime identification
2) Timing layer for an existing strategy
3) Cross-asset confirmation
4) Expectation management
If the spectrum is flat (no peaks above threshold), that is information:
Summary
Harmonic Frequency Visualizer uses a targeted Discrete Fourier Transform across predefined cycle periods to measure amplitude and phase of cyclical components in price. It supports multi-instrument spectrum comparison, resonance detection when several markets share strong energy at the same periods, and a spectrogram heatmap for the chart instrument showing how cycle dominance evolves over time. A dominant cycle oscillator maps phase into a 0–100 timing readout with alerts for peak/trough/midline transitions. It is a cycle context engine designed to complement trend, structure, and risk models, not replace them.
Overview
Harmonic Frequency Visualizer is a cycle-analysis and cross-asset resonance tool that uses a simplified Discrete Fourier Transform (DFT) to measure how strongly specific cycle periods are present in price. It is not a “trend indicator” and it is not trying to predict direction by itself. Its job is to quantify rhythm: which repeating periods (in bars) are currently dominant, whether those cycles are expanding or contracting (phase direction), and whether multiple instruments are sharing the same dominant periods at the same time (resonance).
This indicator has two main output modes:
- Spectrum: a frequency “snapshot” showing amplitude at each tested period for up to five instruments.
- Spectrogram: a history heatmap showing how the spectrum evolves through time (for the chart instrument).
Spectrum
Spectrogram
On top of that, it produces a Dominant Cycle Oscillator derived from the dominant cycle’s phase, which gives a continuous cycle position metric (peak/trough style zones) without repainting.
This is designed for traders who want cycle context the same way they want volatility context: not as a magic signal, but as structure.
What “frequency” and “cycles” mean in trading terms
A cycle period (say 21 bars) means: “a repeating pattern that tends to complete one full oscillation every 21 bars.” If price contains such a pattern, the DFT will detect a strong correlation between price and a 21-bar sine/cosine wave.
Markets do not have perfectly stable periodic motion, but they often show:
- Mean-reverting swings around value.
- Trend pulses with pullback cadence.
- Volatility clustering that creates rhythmic expansions and contractions.
Cycle tools are trying to measure those repeating components, and DFT is the standard mathematical way to do it.
Where DFT comes from (the core idea)
The Discrete Fourier Transform comes from Fourier analysis, a foundational signal processing concept:
Fourier’s idea: any sufficiently well-behaved signal can be expressed as a sum of sine and cosine waves at different frequencies, each with:
- An amplitude (how strong that wave is).
- A phase (where you are within the wave cycle).
In continuous math you get the Fourier Transform. In sampled data (like candles) you use the Discrete Fourier Transform. It converts a time series (price over time) into a frequency description (strength of different cycles).
In markets:
- Time domain: candles and price series.
- Frequency domain: cycle periods and their strengths.
Why sine and cosine, not just sine
A sine wave alone cannot represent every phase alignment cleanly. DFT uses both cosine and sine components because together they form an orthogonal basis that can represent any phase shift.
You can think of it like this:
- Cosine component captures “in-phase” alignment with the cycle.
- Sine component captures “quadrature” (90-degree shifted) alignment.
- Combining them gives full information: amplitude + phase.
Mathematically, a single frequency component can be written as:
- A * cos(ωt + φ)
But DFT estimates A and φ by separately accumulating cosine and sine projections.
How this script implements the DFT (and what it is actually measuring)
This is not a full-spectrum FFT across every frequency. It is a targeted DFT across a fixed set of cycle periods:
Tested periods
The script tests 8 predefined periods:
- 5, 8, 13, 21, 34, 55, 89, 120
These are Fibonacci-like cycle candidates commonly used in cycle/market structure work. The point is not that Fibonacci is magic. The point is that these represent a reasonable spread from short to long rhythms without needing hundreds of frequencies (which would be heavy in Pine).
Normalization step (important)
Before computing the DFT, the script normalizes the series:
- mn = SMA(src, lookback)
- sd = stdev(src, lookback)
- norm = (src - mn) / sd (if sd != 0)
Why normalize:
- DFT amplitude depends on the scale of the input series.
- If you compare BTC and TLT raw prices, the magnitude is meaningless.
- Z-score normalization makes amplitude more comparable across instruments and regimes.
So the spectrum is measuring “cyclical structure in standardized deviations,” not raw dollars.
Projection onto cosine and sine
For each tested period P:
- ω = 2π / P (angular frequency for that period)
- Compute:
- sCos = Σ(norm[k] * cos(ωk))
- sSin = Σ(norm[k] * sin(ωk))
Interpretation:
- You are correlating the last window of normalized price with a cosine wave of period P.
- And also correlating it with a sine wave of period P.
- If the price has a strong P-bar rhythm, these sums grow in magnitude.
Window length detail
The script uses:
- window = min(lookback - 1, 99)
So even if lookback is 200, the internal DFT accumulation caps at 100 bars for performance stability. This is a deliberate trade: stable computation in Pine, while still letting you define normalization lookback and overall context.
Amplitude computation
Once sCos and sSin are computed:
- raw magnitude = sqrt(sCos² + sSin²)
This is the length of the vector (sCos, sSin). That vector length is the standard way to combine the orthogonal components into one strength metric.
Then it scales it into a 0–100 “display amplitude”:
- amp = sqrt(sCos² + sSin²) / lookback * 100 * sensitivity
- amp is capped to 100
So:
- Higher amplitude means stronger alignment with that cycle period.
- Sensitivity is a user control to amplify or damp the display scaling.
Important: amplitude here is not a probability, and it is not guaranteed “signal quality.” It is a standardized “how much of that cycle exists in the recent window” metric.
Phase computation
Phase is computed using atan2(sSin, sCos). That matters because:
- A simple atan(sin/cos) fails in different quadrants.
- atan2 correctly resolves the angle from -π to +π.
Phase tells you where you are within the cycle:
- Two cycles can have same amplitude but opposite phase.
- Phase is what lets you infer “approaching peak vs trough” behavior.
Dominant cycle selection
The script chooses the dominant cycle as the period with the highest amplitude among the tested periods:
- domIdx = argmax(amp)
*domAmp = max amplitude
*domPhase = phase at domIdx
This dominant cycle is used for:
- Spectrogram history matrix (chart symbol).
- Dominant cycle oscillator.
- Data window outputs (dominant period, oscillator value).
Spectrum View: what you see and how to read it
In Spectrum mode, the indicator draws a frequency snapshot for up to five instruments. Each instrument gets a spectrum line (or bars/area depending on style) plotted across the 8 periods on the x-axis, with amplitude (0–100) on the y-axis.
X-axis meaning
Each x position corresponds to a period (5 → 120 bars). You are not looking at “frequency in Hz.” You are looking at “period in bars,” which is more intuitive in trading.
Y-axis meaning
Amplitude is a scaled measure of how strongly that period is present in the recent normalized data. Higher means stronger.
Plot styles
- Waveform: connects amplitude points into a continuous shape, best for seeing spectrum shape.
- Bars: draws vertical bars per period, best for quick comparison.
- Area: similar to waveform but filled toward baseline for emphasis.
Dominant peaks and phase direction labels
The script highlights dominant cycles per symbol (if enabled):
- If max amplitude > 20, it labels that peak with the symbol name.
- If Show Phase Direction is enabled, it appends ▲ or ▼.
Phase direction logic:
- rising = sin(phase) < 0
- ▲ means cycle is in a “rising” phase segment
- ▼ means cycle is in a “falling” phase segment
This is not “price will rise now.” It is “the dominant cycle’s instantaneous phase suggests you are on the upward vs downward half of that oscillation.” In real markets, you use this as context, not as a standalone trade trigger.
It also draws small ▲/▼ markers on secondary peaks (amp > 15) to show phase direction of other meaningful cycles, giving you a richer picture than “one dominant period.”
Resonance Zones: cross-asset harmonic alignment
Resonance is where this tool becomes more than a single-chart curiosity.
What resonance means here
A resonance zone is flagged when at least 3 out of 5 instruments have strong amplitude at the same tested period. Mechanically:
- For each period i:
- Count instruments with amp > 30
- If count >= 3, mark resonance at that period
When resonance is detected:
- A vertical highlight box is drawn behind that period.
- A ⚡ marker is printed at the top.
Interpretation:
- Multiple assets are expressing a similar cycle length at the same time.
- This can indicate macro rhythm, shared liquidity timing, or cross-market synchronization.
This is especially useful when your instrument set includes:
- Rates proxy (TLT), commodities (oil, gold), and crypto indices.
- You can visually spot when markets are “vibrating” together at a shared period.
Resonance is not automatically bullish or bearish. It is telling you “cycle length agreement,” which can help with timing models and contextual trade planning.
Spectrogram View: frequency over time
Spectrum mode is a snapshot. Spectrogram mode adds time evolution.
What a spectrogram is
A spectrogram is a 2D heatmap where:
- Rows = different periods (frequency bands).
- Columns = time history (bars ago → now).
- Color = amplitude strength.
This allows you to see:
- Which cycles are persistent vs fleeting.
- When dominant cycle shifts occur (energy moves from one period to another).
- Cycle regime transitions (short cycles dominating in chop vs longer cycles dominating in trend).
How the script builds the spectrogram matrix
It maintains a matrix with:
- NUM_PERIODS rows (8 periods)
- histBars columns (history length)
Each bar:
- Remove the oldest column.
- Append the newest amplitude array from chartSpec.
So the spectrogram is always a rolling history of the chart symbol’s cycle amplitudes. It does not attempt to store five symbols (too heavy), it focuses on the active chart for time evolution.
Heat coloring
Amplitude values map to a custom gradient:
- Low = dark blue
- Mid = blue/cyan to orange
- High = yellow
This makes dominant energy bands visually obvious. A stable bright band means persistent cycle dominance.
Dominant Cycle Oscillator: phase mapped to a 0–100 oscillator
The oscillator is derived from the dominant cycle phase (chart symbol):
- oscRaw = cos(domPhase)
- oscValue = 50 + 50 * oscRaw (maps -1..1 into 0..100)
Interpretation:
- When cos(phase) ≈ +1, oscillator near 100 (cycle peak zone).
- When cos(phase) ≈ -1, oscillator near 0 (cycle trough zone).
- Midline 50 corresponds to the quarter-cycle transition points.
It also colors the oscillator by phase direction:
- oscRising = sin(domPhase) < 0
- Rising phase = green-ish
- Falling phase = red-ish
This gives you a clean timing reference:
- The dominant period tells you the cycle length.
- The oscillator tells you where you are within that cycle.
It is not forecasting price. It is telling you the current phase position of the strongest detected cycle component.
Alerts and practical timing usage
Alerts are based on the oscillator:
- Cross above 80: dominant cycle entering peak zone.
- Cross below 20: dominant cycle entering trough zone.
- Cross 50: midline cross (phase transition).
In practice, you use these as “timing context” alerts, for example:
- If your trend model is bullish and cycle oscillator enters trough zone, it can hint at a favorable pullback timing window.
- If you are mean-reversion trading and cycle peak zone aligns with resistance, that confluence matters.
Again: cycle timing needs structure confirmation. The oscillator alone is not a trade system.
Multi-instrument design and non-repaint behavior
The indicator requests five external instruments via request.security. It uses:
- close[1] with lookahead_on
This forces the data to be “previous confirmed close” so the spectral calculations do not repaint intra-bar. That matters because cycle measures can change drastically within a bar if you let them use live values.
So:
- Spectra for external symbols are based on confirmed historical closes.
- Chart symbol spectrogram and oscillator are also stable in the sense they depend on confirmed series values (dominant phase updates bar-to-bar).
Key parameters and how they change behavior
Analysis Lookback
Affects normalization and the DFT window cap:
- Higher lookback stabilizes mean/stdev normalization and reduces random shifts.
- Lower lookback makes the tool more reactive but more prone to regime noise.
Because the inner DFT accumulation caps at 100 bars, very high lookback mostly affects normalization rather than the raw projection length.
Sensitivity
Scales displayed amplitude:
- Higher sensitivity makes peaks stand out more.
- Lower sensitivity compresses amplitude.
It is a display control, not a physics constant.
View Mode
- Spectrum: cross-asset snapshot comparison, resonance detection.
- Spectrogram: time evolution of cycle energy for chart symbol.
Show Phase Direction
Adds ▲/▼ markers derived from sin(phase). Useful for quick cycle position intuition, but do not treat ▲ as “buy.”
Show Resonance Zones
Marks periods where many instruments share strong energy. Useful for macro rhythm alignment.
Highlight Dominant Cycles
Labels peaks. If you disable it, the chart becomes cleaner but less informative.
Spectrogram History
Controls how many columns are stored. Higher makes a longer heatmap but costs more drawing.
Limitations and what not to assume
This tool is honest DSP applied to market data, but market data is not a stationary sine wave generator. Key limitations:
- Cycles drift. Dominant period can shift as regime changes.
- The tool only tests 8 candidate periods. If the true dominant period is 30, it will express as energy near 34 or distributed across neighbors.
- Normalization helps comparability, but does not make amplitude “absolute truth.”
- DFT assumes a stable frequency over the window. Markets often violate that.
- Phase-based oscillators are timing aids, not predictors.
This is why the indicator is best used as:
- Context for entries/exits, not a standalone system.
- A way to see when cycle energy concentrates or disperses.
- A way to detect when multiple markets share a timing rhythm.
How to use it properly (workflows)
1) Cycle regime identification
- If short periods (5–13) dominate, market is often choppy, reactive, and mean-reverting.
- If mid periods (21–55) dominate, market often shows swing structure.
- If long periods (89–120) dominate, market can be in slower macro drift, trend legs, or compressed volatility regimes.
2) Timing layer for an existing strategy
- Use your trend model to decide direction.
- Use dominant cycle oscillator to decide timing within that direction.
- Use spectrogram to avoid trading when dominant period is unstable or flipping rapidly.
3) Cross-asset confirmation
- If you see resonance at a period, watch whether your main instrument is also showing strength there.
- Resonance can justify holding a cycle-based timing thesis with more confidence because it is not isolated.
4) Expectation management
If the spectrum is flat (no peaks above threshold), that is information:
- No clean dominant cycle, randomness dominates.
- Cycle-based timing will be unreliable.
Summary
Harmonic Frequency Visualizer uses a targeted Discrete Fourier Transform across predefined cycle periods to measure amplitude and phase of cyclical components in price. It supports multi-instrument spectrum comparison, resonance detection when several markets share strong energy at the same periods, and a spectrogram heatmap for the chart instrument showing how cycle dominance evolves over time. A dominant cycle oscillator maps phase into a 0–100 timing readout with alerts for peak/trough/midline transitions. It is a cycle context engine designed to complement trend, structure, and risk models, not replace them.
开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Or go to backquant.com/
Or go to backquant.com/
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。
开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Or go to backquant.com/
Or go to backquant.com/
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。