Indicator · Pine Script v6 · Own pane

Composite Fractal Behavior (CFB)

by mihakralj

Calculates the Composite Fractal Behavior metric across multiple depth tiers to analyze trend persistence and cycle behavior.

View on GitHub

GitHub stars47on the repository
Pine versionv6current
Lines of code193
Settings5inputs
LicenceMIT
Last update8 months ago28 Feb 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

193 lines of Pine Script v6 from indicators/momentum/cfb.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

cfb.pine
// The MIT License (MIT)
// © mihakralj
//@version=6
indicator("Composite Fractal Behavior (CFB)", "CFB", overlay=false)

//@function Calculates CFB auxiliary value for a single depth
//@param source Price series to analyze
//@param depth Lookback period for fractal pattern analysis
//@param maxSize Maximum buffer size (must be >= depth)
//@returns Ratio representing fractal behavior at specified depth
//@optimized O(n) complexity required for fractal pattern calculation across depth range
cfb_aux(series float source, series int depth, simple int maxSize) =>
    if maxSize < depth
        runtime.error("maxSize must be greater than or equal to depth")
    
    var array<float> buffer = array.new_float(maxSize, na)
    var int head = 0
    var int count = 0
    
    float current = nz(source)
    array.set(buffer, head, current)
    head := (head + 1) % maxSize
    
    if count < maxSize
        count += 1
    
    int effectiveDepth = int(math.min(depth, count - 1))
    int actualCount = math.max(1, count)
    
    if effectiveDepth > 0
        float sumAbs = 0.0
        float sumWeighted = 0.0
        float sumLevel = 0.0
        
        for i = 0 to effectiveDepth - 1
            int idx1 = (head - effectiveDepth + i + maxSize) % maxSize
            int idx2 = (head - effectiveDepth + i + 1 + maxSize) % maxSize
            float val1 = nz(array.get(buffer, idx1))
            float val2 = nz(array.get(buffer, idx2))
            float absDiff = math.abs(val1 - val2)
            
            sumAbs += absDiff
            sumWeighted += absDiff * (effectiveDepth - i)
            sumLevel += val2
        
        int currentIdx = (head - 1 + maxSize) % maxSize
        float currentVal = nz(array.get(buffer, currentIdx))
        float levelCompare = math.abs(effectiveDepth * currentVal - sumLevel)
        
        float result = sumWeighted > 0.0 ? levelCompare / sumWeighted : 0.0
        float compensator = float(effectiveDepth + 1) / float(depth + 1)
        result * compensator
    else
        0.0

//@function Calculates Composite Fractal Behavior across multiple depths
//@param source Price series to analyze
//@param maxDepth Maximum depth level (1-10)
//@param length Smoothing period for CFB values
//@returns CFB value representing dominant cycle period
//@optimized O(n²) complexity required for multi-depth fractal analysis
cfb(series float source, simple int maxDepth, simple int length) =>
    if maxDepth < 1 or maxDepth > 10
        runtime.error("maxDepth must be between 1 and 10")
    if length < 1
        runtime.error("length must be greater than 0")
    
    int numDepths = maxDepth * 2
    int maxBufferSize = int(2 + math.pow(2, maxDepth - 1) * maxDepth * 2)
    
    var array<int> periods = array.new_int(numDepths, 0)
    var array<float> cfbValues = array.new_float(numDepths, 0.0)
    var array<float> smoothed = array.new_float(numDepths, 0.0)
    var array<float> weighted = array.new_float(numDepths, 0.0)
    var bool initialized = false
    
    if not initialized
        initialized := true
        int cumSum = 2
        for i = 0 to numDepths - 1
            int powerIdx = int(i / 2)
            int period = int(math.pow(2, powerIdx))
            array.set(periods, i, cumSum)
            cumSum += period
    
    for i = 0 to numDepths - 1
        int period = array.get(periods, i)
        float cfbVal = cfb_aux(source, period, maxBufferSize)
        array.set(cfbValues, i, cfbVal)
    
    float alpha = 2.0 / (length + 1)
    for i = 0 to numDepths - 1
        float cfbVal = array.get(cfbValues, i)
        float prevSmoothed = array.get(smoothed, i)
        float newSmoothed = na(prevSmoothed) ? cfbVal : alpha * cfbVal + (1 - alpha) * prevSmoothed
        array.set(smoothed, i, newSmoothed)
    
    float factorA = 1.0
    float factorB = 1.0
    
    for i = 0 to numDepths - 1
        float smoothVal = array.get(smoothed, i)
        if i % 2 == 0
            float w = factorB * smoothVal
            array.set(weighted, i, w)
            factorB := factorB * (1.0 - smoothVal)
        else
            float w = factorA * smoothVal
            array.set(weighted, i, w)
            factorA := factorA * (1.0 - smoothVal)
    
    float sumWeightedSq = 0.0
    float sumSq = 0.0
    
    for i = 0 to numDepths - 1
        float w = array.get(weighted, i)
        float wSq = w * w
        sumSq += wSq
        sumWeightedSq += wSq * array.get(periods, i)
    
    float result = sumSq > 0.0 ? sumWeightedSq / sumSq : 0.0
    math.max(1.0, result)

//@function Jurik Moving Average for additional smoothing
//@param source Series to smooth
//@param period Smoothing period
//@param phase Phase adjustment (-100 to 100)
//@param power Power parameter for responsiveness
//@returns Smoothed value
//@optimized Adaptive smoothing with volatility-based responsiveness
jma(series float source, simple int period, simple int phase = 0, simple float power = 0.45) =>
    if period < 1
        runtime.error("period must be greater than 0")
    float phaseRatio = math.min(math.max(phase * 0.01 + 1.5, 0.5), 2.5)
    float beta = power * (period - 1) / (power * (period - 1) + 2)
    float len1 = math.max(math.log(math.sqrt(0.5 * (period - 1))) / math.log(2.0) + 2.0, 0.0)
    float pow1 = math.max(len1 - 2.0, 0.5)
    float len2 = math.sqrt(0.5 * (period - 1)) * len1
    float alpha_volty = 2.0 / (math.max(4.0 * period, 65.0) + 1.0)
    float div = 1.0 / (10.0 + 10.0 * (math.min(math.max(period - 10, 0), 100)) / 100.0)
    
    var float upperBand = na
    var float lowerBand = na
    var float ma1 = na
    var float jma_val = na
    var float vSum = 0.0
    var float det0 = 0.0
    var float det1 = 0.0
    var float avgVolty = na
    var array<float> voltyArray = array.new_float(11, 0.0)
    
    if not na(source)
        float del1 = source - nz(upperBand, source)
        float del2 = source - nz(lowerBand, source)
        float volty = math.abs(del1) == math.abs(del2) ? 0.0 : math.max(math.abs(del1), math.abs(del2))
        
        array.unshift(voltyArray, volty)
        array.pop(voltyArray)
        
        vSum := vSum + (volty - array.get(voltyArray, 10)) * div
        avgVolty := na(avgVolty) ? vSum : avgVolty + alpha_volty * (vSum - avgVolty)
        
        float rvolty = math.min(math.max(avgVolty > 0 ? volty / avgVolty : 1.0, 1.0), math.pow(len1, 1.0 / pow1))
        float pow2 = math.pow(rvolty, pow1)
        float kv = math.pow(len2 / (len2 + 1), math.sqrt(pow2))
        
        upperBand := del1 > 0 ? source : source - kv * del1
        lowerBand := del2 < 0 ? source : source - kv * del2
        
        float alphaAdapt = math.pow(beta, pow2)
        
        ma1 := source + alphaAdapt * (nz(ma1, source) - source)
        det0 := (source - ma1) * (1 - beta) + beta * det0
        
        float ma2 = ma1 + phaseRatio * det0
        det1 := (ma2 - nz(jma_val, source)) * (1 - alphaAdapt) * (1 - alphaAdapt) + alphaAdapt * alphaAdapt * det1
        jma_val := nz(jma_val, source) + det1
    
    jma_val

// ---------- Main loop ----------

i_source = input.source(hlcc4, "Source")
i_depth = input.int(10, "CFB Depth", minval=1, maxval=10)
i_length = input.int(8, "Smooth Length", minval=1)
i_jma_period = input.int(5, "JMA Period", minval=1)
i_jma_phase = input.int(0, "JMA Phase", minval=-100, maxval=100)

cfb_raw = cfb(i_source, i_depth, i_length)
cfb_smoothed = jma(jma(cfb_raw, i_jma_period, i_jma_phase), i_jma_period, i_jma_phase)
cfb_final = math.max(1, math.ceil(cfb_smoothed))

plot(cfb_final, "CFB", color=color.yellow, linewidth=2)

Overview

Composite Fractal Behavior (CFB) evaluates fractal pattern ratios across logarithmic period steps, smooths the resulting index, and applies Jurik Moving Average filtering. Configurable parameters include depth levels, smoothing length, and JMA period and phase settings. The indicator plots in a separate pane.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Volatility & bands

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

pinescriptpinescript-indicatorstechnical-analysistradingview-indicators

Settings

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

SettingTypeDefaultVariable
Sourcesourcehlcc4i_source
CFB Depthint10i_depth
Smooth Lengthint8i_length
JMA Periodint5i_jma_period
JMA Phaseint0i_jma_phase
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

TTM Squeeze

by Alorse
330 stars

This indicator plots a TTM Squeeze momentum oscillator in a separate pane. It compares a Bollinger Band offset to a Keltner Channel offset and marks the zero line white when the difference is non-negative and black when the bands are inside the channel. A line

Indicator v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of TTM Squeeze

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V
218 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector
147 stars

This indicator generates trade entry signals and target levels optimized for 1-hour timeframes, designed for external signal extraction. It calculates 7-period and 16-period EMAs alongside 10-period RSI and ATR filters. Long signals occur when the fast EMA cro

Indicator v5 TrendOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of Signal Strategy 100 Candles of 1H Timeframe

Bubbles Indicator

by capissimo
114 stars

The Bubbles Indicator measures volatility squeezes and expansion bursts using Bollinger Bands combined with a sinusoid oscillator and RSI divergence. It processes price data through scaled Bollinger Bands to highlight volatility changes while confirming trend

Indicator v4 Volatility & bandsOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Bubbles Indicator

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