Indicator · Pine Script v6 · Own pane

FFT Dominant Cycle (Radix-2 FFT)

by mihakralj

This indicator calculates the dominant cycle period of the input source using a Radix-2 Fast Fourier Transform.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code177
Settings4inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

177 lines of Pine Script v6 from lib/numerics/fft/fft.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

fft.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("FFT Dominant Cycle (Radix-2 FFT)", "FFT-DC", overlay=false, precision=2)

// -----------------------
// Helpers
// -----------------------

int ilog2(int n) =>
    // n must be power of 2
    int p = 0
    int x = n
    while x > 1
        x := x / 2
        p += 1
    p

int bitReverse(int x, int bits) =>
    int r = 0
    for i = 0 to bits - 1
        r := (r << 1) | (x & 1)
        x := x >> 1
    r

// In-place iterative radix-2 FFT on arrays re/im of length N
void fft_inplace(float[] re, float[] im, int N) =>
    int bits = ilog2(N)

    // Bit-reversal permutation
    for i = 0 to N - 1
        int j = bitReverse(i, bits)
        if j > i
            float tre = array.get(re, i)
            float tim = array.get(im, i)
            array.set(re, i, array.get(re, j))
            array.set(im, i, array.get(im, j))
            array.set(re, j, tre)
            array.set(im, j, tim)

    // Cooley–Tukey butterflies
    int len = 2
    while len <= N
        int half = len / 2
        float angStep = -2.0 * math.pi / len

        for start = 0 to N - 1 by len
            for k = 0 to half - 1
                float ang = angStep * k
                float wr = math.cos(ang)
                float wi = math.sin(ang)

                int i0 = start + k
                int i1 = i0 + half

                float ur = array.get(re, i0)
                float ui = array.get(im, i0)
                float vr = array.get(re, i1)
                float vi = array.get(im, i1)

                // t = w * v
                float tr = vr * wr - vi * wi
                float ti = vr * wi + vi * wr

                array.set(re, i0, ur + tr)
                array.set(im, i0, ui + ti)
                array.set(re, i1, ur - tr)
                array.set(im, i1, ui - ti)

        len *= 2

// Dominant cycle period via FFT magnitude peak + parabolic interpolation
float dominantPeriod_fft(series float src, int N, int minPeriod, int maxPeriod, float[] win) =>
    int halfN = N / 2
    int minBin = math.max(1, N / maxPeriod)
    int maxBin = math.min(halfN, N / minPeriod)

    // Build windowed input (oldest..newest), imag=0
    float[] re = array.new_float(N, 0.0)
    float[] im = array.new_float(N, 0.0)

    for n = 0 to N - 1
        // src[n] in Pine: n bars ago; so n = N-1 is oldest in the window
        // We want time order oldest..newest in FFT input:
        // oldest = src[N-1], newest = src[0]
        float x = nz(src[N - 1 - n])
        float w = array.get(win, n)
        array.set(re, n, x * w)
        array.set(im, n, 0.0)

    // FFT
    fft_inplace(re, im, N)

    // Find peak magnitude in requested bin range
    float bestMag = na
    int   bestK = minBin

    // We also need neighbor mags for interpolation later.
    // We'll compute mags on-demand because range is small.
    for k = minBin to maxBin
        float rr = array.get(re, k)
        float ii = array.get(im, k)
        float mag = rr * rr + ii * ii
        if na(bestMag) or mag > bestMag
            bestMag := mag
            bestK := k

    // Neighbor magnitudes for interpolation (handle edges)
    float a = 0.0
    float b = bestMag
    float c = 0.0

    if bestK > minBin
        float rrA = array.get(re, bestK - 1)
        float iiA = array.get(im, bestK - 1)
        a := rrA * rrA + iiA * iiA
    else
        a := b

    if bestK < maxBin
        float rrC = array.get(re, bestK + 1)
        float iiC = array.get(im, bestK + 1)
        c := rrC * rrC + iiC * iiC
    else
        c := b

    // Correct parabolic interpolation:
    // shift = 0.5*(a - c)/(a - 2b + c)
    float denom = (a - 2.0 * b + c)
    float shift = math.abs(denom) > 0.0 ? 0.5 * (a - c) / denom : 0.0

    float period = N / (bestK + shift)
    math.max(float(minPeriod), math.min(float(maxPeriod), period))

// -----------------------
// Inputs
// -----------------------

i_source = input.source(close, "Source")
i_window = input.int(64, "Window Size", options=[32, 64, 128])
i_minP   = input.int(4, "Min Period", minval=2, maxval=64)
i_maxP   = input.int(32, "Max Period", minval=4, maxval=64)

// Validate
if i_window != 32 and i_window != 64 and i_window != 128
    runtime.error("Window size must be 32, 64, or 128")
if i_minP < 2
    runtime.error("Min period must be >= 2")
if i_maxP > i_window / 2
    runtime.error("Max period must be <= windowSize/2")

// -----------------------
// Precompute Hanning window once per N
// -----------------------

var int    prevN = na
var float[] win = array.new_float(0)

if na(prevN) or prevN != i_window
    prevN := i_window
    win := array.new_float(i_window, 0.0)
    float twoPiOverN = 2.0 * math.pi / i_window
    for n = 0 to i_window - 1
        array.set(win, n, 0.5 - 0.5 * math.cos(twoPiOverN * n))

// -----------------------
// Main
// -----------------------

float period = na
if bar_index >= i_window
    period := dominantPeriod_fft(i_source, i_window, i_minP, i_maxP, win)

// Plot
plot(period, "Dominant Period", color=color.yellow, linewidth=2)
hline(8,  "Fast Cycle", color=color.green, linestyle=hline.style_dashed)
hline(20, "Slow Cycle", color=color.red,   linestyle=hline.style_dashed)

Overview

FFT Dominant Cycle (Radix-2 FFT) builds a windowed array from the source data, performs an in-place iterative FFT, and identifies the peak magnitude within the specified frequency bins corresponding to min and max periods. The resulting dominant period value is plotted as a line in a separate pane. Window size determines the FFT length, while minPeriod and maxPeriod restrict the search range for the dominant cycle.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosei_source
Window Sizeint64i_window
Min Periodint4i_minP
Max Periodint32i_maxP
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop
261 stars

This indicator demonstrates an experimental graph-style scatter visualization within a separate pane using Pine Script arrays. It tracks two features across recent bars: the single-bar price change and a scaled 14-period Relative Strength Index. Values are loa

Indicator v4 Oscillators & momentum
Updated 4 years ago · None stated GitHub repository of Example: Graph Style - 4th Dimension RSI

KD指標

by TaichiS
219 stars

This script calculates and plots a Stochastic Oscillator (KD indicator) in a separate chart pane. It determines the fast stochastic value over a 9-period lookback, then applies a 3-period Simple Moving Average (SMA) to create the %K line, and a second 3-period

Indicator v4 Oscillators & momentum
Updated 5 years ago · None stated GitHub repository of KD指標

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers