MM Flow
FlowScripts

Perfected FlowScript

Custom tradingview with break

Custom TradingView with Break — Perfected Edition is indexed as 360_custom_tradingview_with_break.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

20.8 KB

Lines

661

Native Signal Candidates

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

8/8 guarded

Pivot High

line 511:5

Trigger

(showPivot && swingHighEvent)

Value

lastSwingHigh

Deps

showPivot:input, swingHighEvent:var

Pivot Low

line 521:5

Trigger

(showPivot && swingLowEvent)

Value

lastSwingLow

Deps

showPivot:input, swingLowEvent:var

Bull Break

line 547:9

Trigger

(showBreak && showShapes) && (bullBreakEvent)

Value

cl

Deps

bullBreakEvent:var, showBreak:input, showShapes:input

Bear Break

line 557:9

Trigger

(showBreak && showShapes) && (bearBreakEvent)

Value

cl

Deps

bearBreakEvent:var, showBreak:input, showShapes:input

Bull Trap

line 571:9

Trigger

(showShapes && useTrapFilter) && (bullTrapEvent)

Value

cl

Deps

bullTrapEvent:var, showShapes:input, useTrapFilter:input

Bear Trap

line 581:9

Trigger

(showShapes && useTrapFilter) && (bearTrapEvent)

Value

cl

Deps

bearTrapEvent:var, showShapes:input, useTrapFilter:input

Near Res

line 594:5

Trigger

(showShapes && nearRes && !bullBreak)

Value

resLevel

Deps

bullBreak:var, nearRes:var, showShapes:input

Near Sup

line 604:5

Trigger

(showShapes && nearSup && !bearBreak)

Value

supLevel

Deps

bearBreak:var, nearSup:var, showShapes:input

360_custom_tradingview_with_break.flowscript

source path: kscripts/perfected/360_custom_tradingview_with_break.flowscript · sha256:ab86fbaab003de3293db7292984a5934134bf046afd8d2cc4fc0b5b52b6e4a2a

hash verified
//@version=2
// ============================================================================
// Custom TradingView with Break — Perfected Edition
// Author: A (@antonykingston) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #breakout, #pivot, #volume, #atr, #composite, #multifactor
//
// Production-quality multi-factor breakout detection combining swing-point
// pivot detection, ATR-based volatility filtering, volume confirmation,
// trend-alignment scoring, and false-break / liquidity-trap rejection.
// Built as a comprehensive price-action breakout toolkit with regime-aware
// color coding and comprehensive shape markers.
//
// Research papers underpinning this design:
//  1. Frykmer & Johnsson (2019), "Pivot Point Trading in the Foreign Exchange
//     Market: A Test for Market Efficiency": exchange rates tend to stop
//     trending at pivot levels — supporting pivot-based breakout detection
//     and inverse pivot implementation.
//  2. Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete
//     Resource for Financial Market Technicians": S/R levels rated 4.41/5
//     by practitioners; breakouts require confirmed close beyond level
//     with volume.
//  3. Bhusal (2025), "Timing the Trap" (SSRN 5276088): documents "stop
//     hunts" / liquidity traps where price briefly breaches a level before
//     reversing; genuine breakouts require follow-through close and volume.
//  4. Crabel (1990), "Playing the Opening Range Breakout": narrow-range
//     breakouts (NR7, IDnr4) are especially reliable; stretch expansion
//     precedes genuine breakouts.
//  5. Brock, Lakonishok & LeBaron (1992), J. Finance: MA crossover and
//     range-breakout rules significantly outperformed cash. Validates
//     breakout strategies as profitable anomalies.
//  6. Wilder (1978), "New Concepts in Technical Trading Systems": ATR enables
//     volatility-scaled breakout thresholds and stop-loss placement.
//  7. Campbell, Ramadorai & Vuolteenaho (2005), NBER 11439: institutional
//     order flow leaves detectable footprints. Volume spikes at breakouts
//     validate informed trading and reject false breaks.
// ============================================================================

define(
    title="Custom TradingView with Break — Perfected Edition",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------

// --- Pivot Detection ---
var pivotLen = input(
    name="pivotLen",
    type="number",
    defaultValue=5,
    label="Pivot Lookback (each side)",
    constraints={min: 2, max: 50, step: 1},
    group="Pivot Detection"
)
var showSwingLevels = input(
    name="showSwingLevels",
    type="boolean",
    defaultValue=true,
    label="Show Swing High/Low Lines",
    group="Pivot Detection"
)

// --- Breakout Levels ---
var breakoutLen = input(
    name="breakoutLen",
    type="number",
    defaultValue=20,
    label="Breakout Level Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Breakout Levels"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length (Filter)",
    constraints={min: 5, max: 100, step: 1},
    group="Breakout Levels"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=0.5,
    label="ATR Breakout Buffer",
    constraints={min: 0.0, max: 3.0, step: 0.1},
    group="Breakout Levels"
)

// --- Volume Confirmation ---
var useVolume = input(
    name="useVolume",
    type="boolean",
    defaultValue=true,
    label="Require Volume Confirmation",
    group="Volume"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Average Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)
var volMinRatio = input(
    name="volMinRatio",
    type="number",
    defaultValue=1.2,
    label="Min Volume Ratio",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Volume"
)

// --- False Break / Trap Filter ---
var useTrapFilter = input(
    name="useTrapFilter",
    type="boolean",
    defaultValue=true,
    label="Enable Trap Filter",
    group="Trap Filter"
)
var trapLookback = input(
    name="trapLookback",
    type="number",
    defaultValue=3,
    label="Trap Confirmation Bars",
    constraints={min: 1, max: 10, step: 1},
    group="Trap Filter"
)
var trapAtrMult = input(
    name="trapAtrMult",
    type="number",
    defaultValue=1.0,
    label="Trap Reversal ATR Multiple",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Trap Filter"
)

// --- Trend Filter ---
var useTrendFilter = input(
    name="useTrendFilter",
    type="boolean",
    defaultValue=true,
    label="Enable Trend Filter",
    group="Trend Filter"
)
var trendLen = input(
    name="trendLen",
    type="number",
    defaultValue=50,
    label="Trend MA Length",
    constraints={min: 10, max: 200, step: 1},
    group="Trend Filter"
)

// --- Display ---
var showPivot = input(
    name="showPivot",
    type="boolean",
    defaultValue=true,
    label="Show Pivot Lines",
    group="Display"
)
var showBreak = input(
    name="showBreak",
    type="boolean",
    defaultValue=true,
    label="Show Breakout Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Highlight Breakout Bars",
    group="Display"
)
var showSR = input(
    name="showSR",
    type="boolean",
    defaultValue=true,
    label="Show S/R Levels",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Shape Markers",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Info Table",
    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 breakUpColor = input(
    name="breakUpColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Break Color",
    group="Colors"
)
var breakDnColor = input(
    name="breakDnColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Break Color",
    group="Colors"
)
var trapColor = input(
    name="trapColor",
    type="color",
    defaultValue="#ffd700",
    label="Trap / False Break Color",
    group="Colors"
)
var pivotColor = input(
    name="pivotColor",
    type="color",
    defaultValue="#ffffff",
    label="Pivot Line Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries cl = bars.close
timeseries op = bars.open
timeseries vol = bars.volume

if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. ATR (WILDER) FOR VOLATILITY FILTERING
// ---------------------------------------------------------------------------
timeseries prevClose = isnan(cl[1]) ? cl : cl[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries atrBuffer = atr * atrMult

// ---------------------------------------------------------------------------
// 4. SWING / PIVOT DETECTION
// ---------------------------------------------------------------------------
// Swing high/low using pivotLen bars on each side.
// Confirmed when the bar at offset [pivotLen] equals the extreme of the
// 2*pivotLen+1 window AND is strictly higher/lower than the immediate
// neighboring bars.
var isSwingHigh = hi[pivotLen] == highest(hi, pivotLen * 2 + 1) && hi[pivotLen] > highest(hi, pivotLen)
var isSwingLow = lo[pivotLen] == lowest(lo, pivotLen * 2 + 1) && lo[pivotLen] < lowest(lo, pivotLen)

// Bar counter for event tracking
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// --- STATIC STATE: Swing Levels ---
static lastSwingHigh = 0.0
static lastSwingLow = 0.0
static prevSwingHigh = 0.0
static prevSwingLow = 0.0
static swingHighBar = 0
static swingLowBar = 0

if (!isLiveUpdate) {
    if (isSwingHigh) {
        if (lastSwingHigh > 0) {
            prevSwingHigh = lastSwingHigh
        }
        lastSwingHigh = hi[pivotLen]
        swingHighBar = barCount - pivotLen
    }
    if (isSwingLow) {
        if (lastSwingLow > 0) {
            prevSwingLow = lastSwingLow
        }
        lastSwingLow = lo[pivotLen]
        swingLowBar = barCount - pivotLen
    }
}

// ---------------------------------------------------------------------------
// 5. SUPPORT / RESISTANCE LEVELS (Donchian-style)
// ---------------------------------------------------------------------------
timeseries resLevel = highest(hi, breakoutLen)
timeseries supLevel = lowest(lo, breakoutLen)
timeseries midLine = (resLevel + supLevel) / 2

// Range width and position
timeseries rangeWidth = resLevel - supLevel
timeseries rangePos = rangeWidth > 0 ? (cl - supLevel) / rangeWidth : 0.5

// ---------------------------------------------------------------------------
// 6. VOLUME CONFIRMATION
// ---------------------------------------------------------------------------
timeseries volAvg = sma(vol, volLookback)
timeseries volRatio = volAvg > 0 ? vol / volAvg : 1.0
var volConfirmed = useVolume ? volRatio >= volMinRatio : true

// ---------------------------------------------------------------------------
// 7. TREND FILTER
// ---------------------------------------------------------------------------
timeseries trendMA = sma(cl, trendLen)
var trendUp = cl > trendMA
var trendDown = cl < trendMA
var trendAlign = trendUp ? 1 : (trendDown ? -1 : 0)

// ---------------------------------------------------------------------------
// 8. MULTI-FACTOR BREAKOUT DETECTION
// ---------------------------------------------------------------------------
// Raw breakout: close beyond prior bar's S/R level
var rawBullBreak = cl > resLevel[1] && cl[1] <= resLevel[1]
var rawBearBreak = cl < supLevel[1] && cl[1] >= supLevel[1]

// ATR-filtered breakout: must exceed level by atrBuffer
var atrBullBreak = rawBullBreak && cl > resLevel[1] + atrBuffer
var atrBearBreak = rawBearBreak && cl < supLevel[1] - atrBuffer

// Volume-confirmed breakout
var volBullBreak = atrBullBreak && volConfirmed
var volBearBreak = atrBearBreak && volConfirmed

// Trend-aligned breakout (price moving in direction of prevailing trend)
var trendBullBreak = volBullBreak && (!useTrendFilter || trendUp)
var trendBearBreak = volBearBreak && (!useTrendFilter || trendDown)

// Final confirmed breakout signals
var bullBreak = trendBullBreak
var bearBreak = trendBearBreak

// ---------------------------------------------------------------------------
// 9. FALSE BREAK / TRAP DETECTION
// ---------------------------------------------------------------------------
// A trap occurs when price briefly breaks a level but reverses within
// trapLookback bars by more than trapAtrMult × ATR.
// We track the last confirmed breakout and check for subsequent reversal.
static lastBullBreakBar = 0
static lastBullBreakPrice = 0.0
static lastBearBreakBar = 0
static lastBearBreakPrice = 0.0

static bullTrapActive = 0
static bearTrapActive = 0

if (!isLiveUpdate) {
    if (bullBreak) {
        lastBullBreakBar = barCount
        lastBullBreakPrice = cl
        bullTrapActive = 0
    }
    if (bearBreak) {
        lastBearBreakBar = barCount
        lastBearBreakPrice = cl
        bearTrapActive = 0
    }

    // Trap detection: if a bull break occurred within lookback and price
    // has reversed below the break level by more than trap buffer
    if (useTrapFilter && lastBullBreakBar > 0 && barCount - lastBullBreakBar <= trapLookback) {
        if (cl < lastBullBreakPrice - atr * trapAtrMult) {
            bullTrapActive = 1
        }
    }
    if (useTrapFilter && lastBearBreakBar > 0 && barCount - lastBearBreakBar <= trapLookback) {
        if (cl > lastBearBreakPrice + atr * trapAtrMult) {
            bearTrapActive = 1
        }
    }
}

var bullTrapEvent = bullTrapActive == 1 && bullTrapActive[1] == 0
var bearTrapEvent = bearTrapActive == 1 && bearTrapActive[1] == 0

// ---------------------------------------------------------------------------
// 10. COMPOSITE SCORE
// ---------------------------------------------------------------------------
// Multi-factor breakout strength score [0, 5]:
//  +1 for raw breakout
//  +1 for ATR buffer exceeded
//  +1 for volume confirmed
//  +1 for trend aligned
//  +1 for no trap detected
var bullScore = 0
var bearScore = 0
if (rawBullBreak) { bullScore = bullScore + 1 }
if (atrBullBreak) { bullScore = bullScore + 1 }
if (volBullBreak) { bullScore = bullScore + 1 }
if (trendBullBreak) { bullScore = bullScore + 1 }
if (bullBreak && bullTrapActive == 0) { bullScore = bullScore + 1 }

if (rawBearBreak) { bearScore = bearScore + 1 }
if (atrBearBreak) { bearScore = bearScore + 1 }
if (volBearBreak) { bearScore = bearScore + 1 }
if (trendBearBreak) { bearScore = bearScore + 1 }
if (bearBreak && bearTrapActive == 0) { bearScore = bearScore + 1 }

// ---------------------------------------------------------------------------
// 11. REGIME DETECTION
// ---------------------------------------------------------------------------
var regimeBull = bullBreak && bullTrapActive == 0
var regimeBear = bearBreak && bearTrapActive == 0
var regimeTrap = bullTrapActive == 1 || bearTrapActive == 1
var regimeNeutral = !regimeBull && !regimeBear && !regimeTrap

var regimeColor = regimeBull ? breakUpColor : (regimeBear ? breakDnColor : (regimeTrap ? trapColor : neutralColor))
var regimeLabel = regimeBull ? "BULL BREAKOUT" : (regimeBear ? "BEAR BREAKOUT" : (regimeTrap ? "TRAP / FALSE BREAK" : "NEUTRAL"))

// ---------------------------------------------------------------------------
// 12. ALERT CONDITIONS & SHAPE MARKERS
// ---------------------------------------------------------------------------
// Breakout events (only on the confirming bar)
var bullBreakEvent = bullBreak && !bullBreak[1]
var bearBreakEvent = bearBreak && !bearBreak[1]

// Swing point events (lagged by pivotLen)
var swingHighEvent = isSwingHigh && barCount - pivotLen > 0
var swingLowEvent = isSwingLow && barCount - pivotLen > 0

// S/R touch events (price near level within ATR buffer)
var nearRes = math.abs(cl - resLevel) < atrBuffer
var nearSup = math.abs(cl - supLevel) < atrBuffer

// ---------------------------------------------------------------------------
// 13. PLOTTING
// ---------------------------------------------------------------------------

// --- Swing Levels (dashed reference lines) ---
if (showSwingLevels && lastSwingHigh > 0) {
    plotLine(
        value=lastSwingHigh,
        width=1,
        colors=[transparency(pivotColor, 40)],
        label=["Swing High"],
        desc=["Last confirmed swing high (pivotLen=" + pivotLen + ")"]
    )
}
if (showSwingLevels && lastSwingLow > 0) {
    plotLine(
        value=lastSwingLow,
        width=1,
        colors=[transparency(pivotColor, 40)],
        label=["Swing Low"],
        desc=["Last confirmed swing low (pivotLen=" + pivotLen + ")"]
    )
}

// --- S/R Levels (Donchian) ---
if (showSR) {
    plotLine(
        value=resLevel,
        width=2,
        colors=[transparency(resColor, 60)],
        label=["Resistance"],
        desc=["Dynamic resistance: " + breakoutLen + "-period highest high"]
    )
    plotLine(
        value=supLevel,
        width=2,
        colors=[transparency(supColor, 60)],
        label=["Support"],
        desc=["Dynamic support: " + breakoutLen + "-period lowest low"]
    )
    plotLine(
        value=midLine,
        width=1,
        colors=[transparency("#ffffff", 30)],
        label=["Midline"],
        desc=["Range midpoint: (resistance + support) / 2"]
    )
}

// --- Pivot Point Markers (on swing-confirming bars) ---
if (showPivot && swingHighEvent) {
    plotShape(
        value=lastSwingHigh,
        shape="triangledown",
        colorIndex=resColor,
        width=2,
        label=["Pivot High"],
        desc=["Swing pivot high confirmed after " + pivotLen + " right-side bars"]
    )
}
if (showPivot && swingLowEvent) {
    plotShape(
        value=lastSwingLow,
        shape="triangleup",
        colorIndex=supColor,
        width=2,
        label=["Pivot Low"],
        desc=["Swing pivot low confirmed after " + pivotLen + " right-side bars"]
    )
}

// --- Breakout Highlight Fill (breakFlag histogram) ---
if (showFill) {
    var breakFlag = bullBreak ? 1 : (bearBreak ? -1 : 0)
    var fillColor = bullBreak ? breakUpColor : (bearBreak ? breakDnColor : "#00000000")
    plotBar(
        value=breakFlag,
        colors=[transparency(fillColor, 50)],
        width=1,
        label=["Breakout Zone"],
        desc=["Breakout zone flag: +1 = bull, -1 = bear, 0 = neutral"]
    )
}

// --- Breakout Markers ---
if (showBreak && showShapes) {
    if (bullBreakEvent) {
        plotShape(
            value=cl,
            shape="triangleup",
            colorIndex=breakUpColor,
            width=3,
            label=["Bull Break"],
            desc=["Confirmed bullish breakout: close > resistance + ATR buffer, volume confirmed, trend aligned"]
        )
    }
    if (bearBreakEvent) {
        plotShape(
            value=cl,
            shape="triangledown",
            colorIndex=breakDnColor,
            width=3,
            label=["Bear Break"],
            desc=["Confirmed bearish breakout: close < support − ATR buffer, volume confirmed, trend aligned"]
        )
    }
}

// --- Trap / False Break Markers ---
if (showShapes && useTrapFilter) {
    if (bullTrapEvent) {
        plotShape(
            value=cl,
            shape="xcross",
            colorIndex=trapColor,
            width=3,
            label=["Bull Trap"],
            desc=["False bullish breakout: price reversed below break level by >" + trapAtrMult + "×ATR"]
        )
    }
    if (bearTrapEvent) {
        plotShape(
            value=cl,
            shape="xcross",
            colorIndex=trapColor,
            width=3,
            label=["Bear Trap"],
            desc=["False bearish breakout: price reversed above break level by >" + trapAtrMult + "×ATR"]
        )
    }
}

// --- S/R Touch Markers (subtle diamonds) ---
if (showShapes && nearRes && !bullBreak) {
    plotShape(
        value=resLevel,
        shape="diamond",
        colorIndex=transparency(resColor, 60),
        width=1,
        label=["Near Res"],
        desc=["Price near resistance level within ATR buffer"]
    )
}
if (showShapes && nearSup && !bearBreak) {
    plotShape(
        value=supLevel,
        shape="diamond",
        colorIndex=transparency(supColor, 60),
        width=1,
        label=["Near Sup"],
        desc=["Price near support level within ATR buffer"]
    )
}

// --- Volume Confirmation Bars (subtle background) ---
if (showBreak && useVolume) {
    var volConfirmVal = volConfirmed ? 1 : 0
    plotBar(
        value=volConfirmVal,
        colors=[transparency("#ffffff", 20)],
        width=1,
        label=["Vol Confirm"],
        desc=["Volume confirmed: ratio >= " + volMinRatio + "× average"]
    )
}

// ---------------------------------------------------------------------------
// 14. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var trendText = trendAlign > 0 ? "UP" : (trendAlign < 0 ? "DOWN" : "FLAT")
    var trendColor = trendAlign > 0 ? breakUpColor : (trendAlign < 0 ? breakDnColor : neutralColor)

    plotTable(
        data=[
            ["Custom TV Break — Perfected", regimeLabel],
            ["Trend", trendText],
            ["Resistance", resLevel[0]],
            ["Support", supLevel[0]],
            ["Range Width", rangeWidth[0]],
            ["Range Position", rangePos[0]],
            ["ATR", atr[0]],
            ["Vol Ratio", volRatio[0]],
            ["Bull Score", bullScore],
            ["Bear Score", bearScore],
            ["Swing High", lastSwingHigh],
            ["Swing Low", lastSwingLow]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}