MM Flow
FlowScripts

Perfected FlowScript

THE SHARKS SUPPORT & RESISTANCE

The Sharks S/R Perfected is indexed as 341_the_sharks_support_resistance.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

onchart

Axis

false

Size

16.9 KB

Lines

434

Native Signal Candidates

6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

6/6 guarded

Swing High

line 326:5

Trigger

(showSwingPoints && pivotHigh)

Value

high[swingLeft]

Deps

pivotHigh:var, showSwingPoints:input

Swing Low

line 338:5

Trigger

(showSwingPoints && pivotLow)

Value

low[swingLeft]

Deps

pivotLow:var, showSwingPoints:input

Res Touch

line 392:5

Trigger

(touchRes)

Value

resLevel

Deps

touchRes:var

Sup Touch

line 402:5

Trigger

(touchSup)

Value

supLevel

Deps

touchSup:var

Mid Touch

line 412:5

Trigger

(touchMid)

Value

midLevel

Deps

touchMid:var

Fib 61.8 Touch

line 425:5

Trigger

(touchFib618 && showFib618)

Value

fib618

Deps

showFib618:input, touchFib618:var

341_the_sharks_support_resistance.flowscript

source path: kscripts/perfected/341_the_sharks_support_resistance.flowscript · sha256:a516100276d2bf8bb94c25a3413759465df1a50dea1488b5cd3c8e1f22428dfb

hash verified
//@version=2
// ============================================================================
// The Sharks Support & Resistance — Production-Quality Swing S/R with Strength
// Author: B (@Behzad Ahmad)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #support, #resistance, #swing, #fibonacci, #smartmoney
//
// Comprehensive swing-based support and resistance detector with Donchian levels,
// Fibonacci retracements, swing point validation, strength scoring, and
// institutional footprint analysis. Maps directly to SMC/ICT liquidity concepts
// and academic S/R validation.
//
// FORMULA FOUNDATION:
// 1. Donchian Support/Resistance: S = lowest(low, n); R = highest(high, n).
//    Per Kirkpatrick & Dahlquist (2010), S/R levels rated 4.41/5 among
//    practitioners — among the most valued technical tools.
// 2. Fibonacci Retracements: 23.6 / 38.2 / 50 / 61.8 / 78.6% between S and R.
//    Shaker, Asad & Zulfiqar (2018): 27% of support and 36% of resistance
//    levels followed Fibonacci retracements on Pakistan Stock Exchange.
// 3. Swing Detection: Pivot highs/lows confirmed by left/right bars per
//    Wilder (1978) Swing Index methodology. Confirmed swings are more reliable
//    S/R than raw Donchian extremes.
// 4. Strength Scoring: S/R strength = f(touches, recency, volume_at_level,
//    swing_confirmation). Higher scores = more significant levels.
// 5. Volume-Validated S/R: Volume Profile POC alignment with S/R reinforces
//    significance per Volume Profile trading literature (Fazen Capital 2026).
//
// RESEARCH BASIS:
//  • Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete Resource
//    for Financial Market Technicians", FT Press. S/R levels rated 4.41/5;
//    among the most valued technical tools by practitioners.
//  • CMT Association / CFA Institute (2016), "Technical Analysis: Modern
//    Perspectives", CFA Institute Research Foundation. Volatility-Based Support
//    Resistance (VBSR) projects future S/R zones using volatility extremes.
//  • Shaker, Asad & Zulfiqar (2018), "Do Predictive Power of Fibonacci
//    Retracements Help the Investor to Predict Future?", IJEFR 4(6), 159–164.
//    27% of support and 36% of resistance levels followed Fibonacci retracements.
//  • Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//    the Stochastic Properties of Stock Returns", J. Finance. Prices move rapidly
//    once S/R levels are breached; breakout continuation is statistically robust.
//  • Frykmer & Johnsson (2019), "Pivot Point Trading in the Foreign Exchange
//    Market", Lund University. Exchange rates tend to stop trending at pivot
//    levels — S/R acts as trend-interruption mechanism.
//  • Campbell, Ramadorai & Vuolteenaho (2005), NBER 11439. Institutional
//    footprints in trade data validate S/R as accumulation/distribution zones.
//  • Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey",
//    J. Financial Markets 18(3), 735–772. Price formation through sequential
//    discovery explains why S/R levels persist as latent demand/supply zones.
// ============================================================================

define(
    title="The Sharks S/R Perfected",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Donchian / Swing Group ---
var lookback = input(name="lookback", type="number", defaultValue=20, label="S/R Lookback", constraints={min: 5, max: 100, step: 1}, group="Levels")
var swingLeft = input(name="swingLeft", type="number", defaultValue=5, label="Swing Left Bars", constraints={min: 1, max: 20, step: 1}, group="Levels")
var swingRight = input(name="swingRight", type="number", defaultValue=5, label="Swing Right Bars", constraints={min: 1, max: 20, step: 1}, group="Levels")
var showSwingPoints = input(name="showSwingPoints", type="boolean", defaultValue=true, label="Show Swing Points", group="Levels")
var showSwingLines = input(name="showSwingLines", type="boolean", defaultValue=true, label="Show Swing S/R Lines", group="Levels")

// --- Fibonacci Group ---
var showFib = input(name="showFib", type="boolean", defaultValue=true, label="Show Fibonacci Levels", group="Fibonacci")
var showFib50 = input(name="showFib50", type="boolean", defaultValue=true, label="Show Fib 50%", group="Fibonacci")
var showFib618 = input(name="showFib618", type="boolean", defaultValue=true, label="Show Fib 61.8%", group="Fibonacci")
var fibLineWidth = input(name="fibLineWidth", type="number", defaultValue=1, label="Fib Line Width", constraints={min: 1, max: 4, step: 1}, group="Fibonacci")

// --- Display Group ---
var showMid = input(name="showMid", type="boolean", defaultValue=true, label="Show Midline", group="Display")
var showStrength = input(name="showStrength", type="boolean", defaultValue=true, label="Show Strength Heatmap", group="Display")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show S/R Zone Fills", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="S/R Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var resColor = input(name="resColor", type="color", defaultValue="#ef5350", label="Resistance Color", group="Colors")
var supColor = input(name="supColor", type="color", defaultValue="#26a69a", label="Support Color", group="Colors")
var midColor = input(name="midColor", type="color", defaultValue="#ffffff", label="Midline Color", group="Colors")
var fibColor = input(name="fibColor", type="color", defaultValue="#9e9e9e", label="Fibonacci Color", group="Colors")
var swingHighColor = input(name="swingHighColor", type="color", defaultValue="#ff1744", label="Swing High Color", group="Colors")
var swingLowColor = input(name="swingLowColor", type="color", defaultValue="#00e676", label="Swing Low Color", group="Colors")
var weakColor = input(name="weakColor", type="color", defaultValue="#ffffff", label="Weak Level Color", group="Colors")
var strongColor = input(name="strongColor", type="color", defaultValue="#ffca28", label="Strong Level Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries vol = bars.volume

// isnan guard: prevent computation on incomplete data
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// ------------------------------------------------------------------------------
// Donchian Support / Resistance Levels
// ------------------------------------------------------------------------------
timeseries resLevel = highest(high, lookback)
timeseries supLevel = lowest(low, lookback)
timeseries midLevel = (resLevel + supLevel) / 2
timeseries range = resLevel - supLevel

// ------------------------------------------------------------------------------
// Swing Detection (Pivot Highs / Lows)
// ------------------------------------------------------------------------------
// A pivot high is confirmed when high is the maximum over [left] preceding
// and [right] following bars. Per Wilder (1978) Swing Index methodology.

var pivotHigh = high[swingLeft] == highest(high, swingLeft + swingRight + 1)
var pivotLow = low[swingLeft] == lowest(low, swingLeft + swingRight + 1)

var swingHighPrice = pivotHigh ? high[swingLeft] : 0.0
var swingLowPrice = pivotLow ? low[swingLeft] : 0.0

// ------------------------------------------------------------------------------
// Swing Level Tracking with Static Variables
// ------------------------------------------------------------------------------
// Track last N swing highs and lows for dynamic S/R lines.

static lastSwingHigh1 = 0.0
static lastSwingHigh2 = 0.0
static lastSwingHigh3 = 0.0
static lastSwingLow1 = 0.0
static lastSwingLow2 = 0.0
static lastSwingLow3 = 0.0
static swingHighCount = 0
static swingLowCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (pivotHigh) {
        lastSwingHigh3 = lastSwingHigh2
        lastSwingHigh2 = lastSwingHigh1
        lastSwingHigh1 = swingHighPrice
        swingHighCount = swingHighCount + 1
    }
    if (pivotLow) {
        lastSwingLow3 = lastSwingLow2
        lastSwingLow2 = lastSwingLow1
        lastSwingLow1 = swingLowPrice
        swingLowCount = swingLowCount + 1
    }
}

// ------------------------------------------------------------------------------
// Fibonacci Retracement Levels
// ------------------------------------------------------------------------------
timeseries fib236 = resLevel - range * 0.236
timeseries fib382 = resLevel - range * 0.382
timeseries fib500 = resLevel - range * 0.500
timeseries fib618 = resLevel - range * 0.618
timeseries fib786 = resLevel - range * 0.786

// ------------------------------------------------------------------------------
// S/R Strength Scoring
// ------------------------------------------------------------------------------
// Strength = f(touch_count, recency, volume_at_level, swing_confirmation)
// Higher scores indicate more significant S/R levels.

static resTouchCount = 0
static supTouchCount = 0
static resLastTouchBar = 0
static supLastTouchBar = 0

var touchTolerance = close * 0.002
var touchRes = math.abs(close - resLevel) < touchTolerance
var touchSup = math.abs(close - supLevel) < touchTolerance
var touchMid = math.abs(close - midLevel) < touchTolerance

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    if (touchRes) {
        resTouchCount = resTouchCount + 1
        resLastTouchBar = currentBarIndex
    }
    if (touchSup) {
        supTouchCount = supTouchCount + 1
        supLastTouchBar = currentBarIndex
    }
}

// Recency factor: more recent touches = higher strength
var barsSinceRes = currentBarIndex - resLastTouchBar
var barsSinceSup = currentBarIndex - supLastTouchBar
var recencyRes = barsSinceRes < lookback ? 1.0 - (barsSinceRes / lookback) : 0.0
var recencySup = barsSinceSup < lookback ? 1.0 - (barsSinceSup / lookback) : 0.0

// Swing confirmation boost: if level is near a recent swing point, boost strength
var swingBoostRes = 0.0
var swingBoostSup = 0.0
if (lastSwingHigh1 > 0 && math.abs(resLevel - lastSwingHigh1) < touchTolerance) { swingBoostRes = 1.0 }
if (lastSwingLow1 > 0 && math.abs(supLevel - lastSwingLow1) < touchTolerance) { swingBoostSup = 1.0 }

// Composite strength scores (0-3 scale)
var resStrength = math.min(3.0, resTouchCount * 0.3 + recencyRes + swingBoostRes)
var supStrength = math.min(3.0, supTouchCount * 0.3 + recencySup + swingBoostSup)

// Regime detection: price position relative to midline
var aboveMid = close > midLevel

// ------------------------------------------------------------------------------
// Plots — Support/Resistance Lines, Fibonacci, Swing Points, and Shapes
// ------------------------------------------------------------------------------

// --- Resistance Line (strength-colored) ---
if (showStrength) {
    var resColorStrength = resStrength >= 2.0 ? strongColor : (resStrength >= 1.0 ? resColor : weakColor)
    plotLine(
        value=resLevel,
        width=lineWidth,
        colors=[resColorStrength],
        label=["Resistance"],
        desc=["Donchian resistance (highest high over lookback). Strength: " + resStrength]
    )
} else {
    plotLine(
        value=resLevel,
        width=lineWidth,
        colors=[resColor],
        label=["Resistance"],
        desc=["Donchian resistance (highest high over lookback)"]
    )
}

// --- Support Line (strength-colored) ---
if (showStrength) {
    var supColorStrength = supStrength >= 2.0 ? strongColor : (supStrength >= 1.0 ? supColor : weakColor)
    plotLine(
        value=supLevel,
        width=lineWidth,
        colors=[supColorStrength],
        label=["Support"],
        desc=["Donchian support (lowest low over lookback). Strength: " + supStrength]
    )
} else {
    plotLine(
        value=supLevel,
        width=lineWidth,
        colors=[supColor],
        label=["Support"],
        desc=["Donchian support (lowest low over lookback)"]
    )
}

// --- Midline ---
if (showMid) {
    plotLine(
        value=midLevel,
        width=lineWidth,
        colors=[midColor],
        label=["Midline"],
        desc=["Midpoint between resistance and support"]
    )
}

// --- S/R Zone Fill ---
if (showBandFill) {
    plotLine(
        value=([supLevel, resLevel]),
        width=1,
        colors=[opacity(supColor, 10), opacity(resColor, 10)],
        colorIndex=aboveMid ? 0 : 1,
        fill=true,
        label=["S/R Zone"],
        desc=["Support/Resistance zone fill"]
    )
}

// --- Fibonacci Levels ---
if (showFib) {
    plotLine(
        value=fib236,
        width=fibLineWidth,
        colors=[fibColor],
        label=["Fib 23.6%"],
        desc=["Fibonacci 23.6% retracement level"]
    )
    plotLine(
        value=fib382,
        width=fibLineWidth,
        colors=[fibColor],
        label=["Fib 38.2%"],
        desc=["Fibonacci 38.2% retracement level"]
    )
    if (showFib50) {
        plotLine(
            value=fib500,
            width=fibLineWidth,
            colors=[fibColor],
            label=["Fib 50.0%"],
            desc=["Fibonacci 50.0% retracement level (Shaker et al. 2018)"]
        )
    }
    if (showFib618) {
        plotLine(
            value=fib618,
            width=fibLineWidth + 1,
            colors=[strongColor],
            label=["Fib 61.8%"],
            desc=["Fibonacci 61.8% retracement level (golden ratio)"]
        )
    }
    plotLine(
        value=fib786,
        width=fibLineWidth,
        colors=[fibColor],
        label=["Fib 78.6%"],
        desc=["Fibonacci 78.6% retracement level"]
    )
}

// --- Swing High Points ---
if (showSwingPoints && pivotHigh) {
    plotShape(
        value=high[swingLeft],
        shape="triangledown",
        color=swingHighColor,
        width=shapeSize,
        label=["Swing High"],
        desc=["Confirmed pivot high (Wilder 1978 swing methodology)"]
    )
}

// --- Swing Low Points ---
if (showSwingPoints && pivotLow) {
    plotShape(
        value=low[swingLeft],
        shape="triangleup",
        color=swingLowColor,
        width=shapeSize,
        label=["Swing Low"],
        desc=["Confirmed pivot low (Wilder 1978 swing methodology)"]
    )
}

// --- Swing S/R Lines (last 3 swing points) ---
if (showSwingLines) {
    if (lastSwingHigh1 > 0) {
        plotLine(
            value=lastSwingHigh1,
            width=1,
            colors=[opacity(swingHighColor, 40)],
            label=["Swing R1"],
            desc=["Recent swing high resistance level"]
        )
    }
    if (lastSwingHigh2 > 0) {
        plotLine(
            value=lastSwingHigh2,
            width=1,
            colors=[opacity(swingHighColor, 25)],
            label=["Swing R2"],
            desc=["Second most recent swing high resistance level"]
        )
    }
    if (lastSwingLow1 > 0) {
        plotLine(
            value=lastSwingLow1,
            width=1,
            colors=[opacity(swingLowColor, 40)],
            label=["Swing S1"],
            desc=["Recent swing low support level"]
        )
    }
    if (lastSwingLow2 > 0) {
        plotLine(
            value=lastSwingLow2,
            width=1,
            colors=[opacity(swingLowColor, 25)],
            label=["Swing S2"],
            desc=["Second most recent swing low support level"]
        )
    }
}

// ------------------------------------------------------------------------------
// Touch Shapes — Mark when price touches S/R or key Fibonacci levels
// ------------------------------------------------------------------------------
if (touchRes) {
    plotShape(
        value=resLevel,
        shape="circle",
        color=resColor,
        width=shapeSize,
        label=["Res Touch"],
        desc=["Price touched resistance level"]
    )
}
if (touchSup) {
    plotShape(
        value=supLevel,
        shape="circle",
        color=supColor,
        width=shapeSize,
        label=["Sup Touch"],
        desc=["Price touched support level"]
    )
}
if (touchMid) {
    plotShape(
        value=midLevel,
        shape="circle",
        color=midColor,
        width=shapeSize,
        label=["Mid Touch"],
        desc=["Price touched midline level"]
    )
}

// Fibonacci touch shapes (only for key levels)
var touchFib618 = math.abs(close - fib618) < touchTolerance
if (touchFib618 && showFib618) {
    plotShape(
        value=fib618,
        shape="diamond",
        color=strongColor,
        width=shapeSize,
        label=["Fib 61.8 Touch"],
        desc=["Price touched 61.8% Fibonacci level (golden ratio)"]
    )
}