MM Flow
FlowScripts

Perfected FlowScript

SCF ICHIMOKU

SCF Ichimoku — Perfected Edition is indexed as 074_scf_ichimoku.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

14.2 KB

Lines

347

Native Signal Candidates

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

4/4 guarded

TK Cross Bull

line 265:9

Trigger

(showShapes) && (tkCrossUp)

Value

tenkan

Deps

showShapes:input, tkCrossUp:var

TK Cross Bear

line 275:9

Trigger

(showShapes) && (tkCrossDown)

Value

tenkan

Deps

showShapes:input, tkCrossDown:var

Kumo Break Up

line 289:9

Trigger

(showShapes) && (kumoBreakUp)

Value

c

Deps

kumoBreakUp:var, showShapes:input

Kumo Break Down

line 299:9

Trigger

(showShapes) && (kumoBreakDown)

Value

c

Deps

kumoBreakDown:var, showShapes:input

074_scf_ichimoku.flowscript

source path: kscripts/perfected/074_scf_ichimoku.flowscript · sha256:a72afdb752681c9d9e837e313ce7bcb25678b9bf574aa73bc9f638c7ce4072d2

hash verified
//@version=2
// ============================================================================
// SCF Ichimoku — Perfected Edition
// Author: kiyotaka (@kiyotaka) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #ichimoku, #cloud, #trend, #tkcross, #momentum, #regime
//
// Production-quality academically-grounded Ichimoku Cloud system with full
// component visualization, cloud fill, regime detection by price position,
// TK cross shape markers, and stateful tracking.
//
// FORMULA FOUNDATION:
// 1. Tenkan-sen (Conversion Line): (Highest High + Lowest Low) / 2 over N1 periods
// 2. Kijun-sen (Base Line): (Highest High + Lowest Low) / 2 over N2 periods
// 3. Senkou Span A (Leading Span A): (Tenkan + Kijun) / 2, displaced forward N3
// 4. Senkou Span B (Leading Span B): (Highest High + Lowest Low) / 2 over N4,
//    displaced forward N3
// 5. Chikou Span (Lagging Span): Close price, displaced backward N3
//    per Hosoda (Goichi Hosoda), 1930s publication; popularized in Western
//    literature by Murphy (1999), "Technical Analysis of the Financial Markets".
//
// REGIME DETECTION:
//  • Price Above Cloud: bullish trend (Senkou A > Senkou B adds green cloud)
//  • Price Below Cloud: bearish trend (Senkou A < Senkou B adds red cloud)
//  • Price Inside Cloud: neutral / consolidation zone
//  • TK Cross: Tenkan crosses above Kijun = bullish signal; below = bearish
//    per standard Ichimoku interpretation (Murphy 1999; CMT Association 2016).
//
// RESEARCH BASIS:
//  • Murphy, J.J. (1999). "Technical Analysis of the Financial Markets".
//    NYIF. Chapter 10: Ichimoku as a complete trend-following system with
//    built-in support/resistance, momentum, and direction signals.
//  • Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing", AQR Capital. Trend-following has delivered positive returns
//    since 1880 across all major asset classes. Ichimoku cloud positioning
//    operationalizes trend-following entry/exit rules.
//  • CMT Association / CFA Institute (2016). "Technical Analysis: Modern
//    Perspectives". Ichimoku as an integrated system: trend, momentum, S/R,
//    and timing in one overlay. Cloud thickness ∝ trend strength.
//  • Zakamulin (2023), "Optimal Trend-Following with Transaction Costs".
//    Optimal trend-following resembles MA crossover rules; Ichimoku's TK
//    cross + cloud filter provide a robust two-factor confirmation.
//  • Brock, Lakonishok & LeBaron (1992), J. Finance. MA crossover rules
//    significantly outperformed buy-and-hold; Ichimoku's multi-line
//    confirmation reduces false signals vs. single MA crossovers.
// ============================================================================

define(
    title="SCF Ichimoku — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Ichimoku Periods ---
var tenkanLen = input(name="tenkanLen", type="number", defaultValue=9, label="Tenkan-sen Length", constraints={min: 2, max: 100, step: 1}, group="Ichimoku Periods")
var kijunLen = input(name="kijunLen", type="number", defaultValue=26, label="Kijun-sen Length", constraints={min: 2, max: 200, step: 1}, group="Ichimoku Periods")
var senkouBLen = input(name="senkouBLen", type="number", defaultValue=52, label="Senkou Span B Length", constraints={min: 2, max: 300, step: 1}, group="Ichimoku Periods")
var displace = input(name="displace", type="number", defaultValue=26, label="Cloud Displacement (forward)", constraints={min: 0, max: 100, step: 1}, group="Ichimoku Periods")

// --- Display ---
var showTenkan = input(name="showTenkan", type="boolean", defaultValue=true, label="Show Tenkan-sen", group="Display")
var showKijun = input(name="showKijun", type="boolean", defaultValue=true, label="Show Kijun-sen", group="Display")
var showCloud = input(name="showCloud", type="boolean", defaultValue=true, label="Show Cloud (Senkou A/B)", group="Display")
var showChikou = input(name="showChikou", type="boolean", defaultValue=true, label="Show Chikou Span", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show TK Cross Shapes", group="Display")
var showPriceRegime = input(name="showPriceRegime", type="boolean", defaultValue=true, label="Show Price Regime Fill", group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bull Cloud Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bear Cloud Color", group="Colors")
var tenkanCol = input(name="tenkanCol", type="color", defaultValue="#ff9800", label="Tenkan-sen Color", group="Colors")
var kijunCol = input(name="kijunCol", type="color", defaultValue="#2196f3", label="Kijun-sen Color", group="Colors")
var chikouCol = input(name="chikouCol", type="color", defaultValue="#9c27b0", label="Chikou Span Color", group="Colors")
var tkCrossBull = input(name="tkCrossBull", type="color", defaultValue="#00e676", label="TK Cross Bullish Color", group="Colors")
var tkCrossBear = input(name="tkCrossBear", type="color", defaultValue="#ff1744", label="TK Cross Bearish Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries c = pxTS.close

if (isnan(c[0])) {
    return
}

// ------------------------------------------------------------------------------
// Ichimoku Component Computation
// ------------------------------------------------------------------------------
// Standard Ichimoku formulas per Hosoda / Murphy (1999).

// Tenkan-sen (Conversion Line): midpoint of highest high and lowest low over N1
var tenkan = (highest(h, tenkanLen) + lowest(l, tenkanLen)) / 2.0

// Kijun-sen (Base Line): midpoint of highest high and lowest low over N2
var kijun = (highest(h, kijunLen) + lowest(l, kijunLen)) / 2.0

// Senkou Span A (Leading Span A): midpoint of Tenkan + Kijun, displaced forward
var senkouA = (tenkan + kijun) / 2.0

// Senkou Span B (Leading Span B): midpoint over N4, displaced forward
var senkouB = (highest(h, senkouBLen) + lowest(l, senkouBLen)) / 2.0

// Chikou Span (Lagging Span): close displaced backward
var chikou = c

// ------------------------------------------------------------------------------
// Regime Detection — Price Position Relative to Cloud
// ------------------------------------------------------------------------------
// Standard Ichimoku interpretation (Murphy 1999; CMT Association 2016):
//   Price above cloud → bullish
//   Price below cloud → bearish
//   Price inside cloud → neutral / consolidation

var cloudTop = math.max(senkouA, senkouB)
var cloudBottom = math.min(senkouA, senkouB)

var priceAboveCloud = c > cloudTop
var priceBelowCloud = c < cloudBottom
var priceInCloud = !priceAboveCloud && !priceBelowCloud

var regime = priceAboveCloud ? 1 : (priceBelowCloud ? -1 : 0)
// 1 = bull, -1 = bear, 0 = neutral

// Cloud color: Senkou A above B = green (bullish cloud); else red (bearish cloud)
var cloudBull = senkouA >= senkouB
var cloudFillColor = cloudBull ? opacity(upColor, 25) : opacity(dnColor, 25)

// ------------------------------------------------------------------------------
// TK Cross Detection
// ------------------------------------------------------------------------------
// Tenkan-sen crossing above Kijun-sen = bullish TK cross (standard signal)
// Tenkan-sen crossing below Kijun-sen = bearish TK cross

var tkCrossUp = tenkan > kijun && !isnan(tenkan[1]) && tenkan[1] <= kijun[1]
var tkCrossDown = tenkan < kijun && !isnan(tenkan[1]) && tenkan[1] >= kijun[1]

// Kumo (cloud) breakout: price crossing above/below cloud
var kumoBreakUp = c > cloudTop && !isnan(c[1]) && c[1] <= highest(senkouA[1], senkouB[1])
var kumoBreakDown = c < cloudBottom && !isnan(c[1]) && c[1] >= lowest(senkouA[1], senkouB[1])

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks TK cross counts, regime duration, cloud thickness, and session extremes.

static lastRegime = 0
static regimeChangeCount = 0
static tkCrossBullCount = 0
static tkCrossBearCount = 0
static kumoBreakUpCount = 0
static kumoBreakDownCount = 0
static sessionHighTenkan = -999999.0
static sessionLowTenkan = 999999.0
static maxCloudThickness = 0.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (tenkan > sessionHighTenkan) {
        sessionHighTenkan = tenkan
    }
    if (tenkan < sessionLowTenkan) {
        sessionLowTenkan = tenkan
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (tkCrossUp) {
        tkCrossBullCount = tkCrossBullCount + 1
    }
    if (tkCrossDown) {
        tkCrossBearCount = tkCrossBearCount + 1
    }
    if (kumoBreakUp) {
        kumoBreakUpCount = kumoBreakUpCount + 1
    }
    if (kumoBreakDown) {
        kumoBreakDownCount = kumoBreakDownCount + 1
    }

    var cloudThickness = math.abs(senkouA - senkouB)
    if (cloudThickness > maxCloudThickness) {
        maxCloudThickness = cloudThickness
    }
}

// ------------------------------------------------------------------------------
// Plots — Cloud Fill, Lines, Shapes, and Regime Overlay
// ------------------------------------------------------------------------------

// --- Cloud Fill (Senkou Span A vs Senkou Span B) ---
if (showCloud) {
    plotLine(
        value=[senkouA, senkouB],
        width=1,
        colors=[upColor, dnColor],
        colorIndex=cloudBull ? 0 : 1,
        fill=true,
        label=["Senkou Span A", "Senkou Span B"],
        desc=["Leading Span A (Tenkan+Kijun midpoint, displaced)", "Leading Span B (long-term midpoint, displaced)"]
    )
}

// --- Tenkan-sen (Conversion Line) ---
if (showTenkan) {
    plotLine(
        value=tenkan,
        width=2,
        colors=[tenkanCol],
        label=["Tenkan-sen"],
        desc=["Conversion Line — short-term equilibrium (" + tenkanLen + ")"]
    )
}

// --- Kijun-sen (Base Line) ---
if (showKijun) {
    plotLine(
        value=kijun,
        width=2,
        colors=[kijunCol],
        label=["Kijun-sen"],
        desc=["Base Line — medium-term equilibrium (" + kijunLen + ")"]
    )
}

// --- Chikou Span (Lagging Span) ---
if (showChikou) {
    plotLine(
        value=chikou,
        width=1,
        colors=[opacity(chikouCol, 50)],
        label=["Chikou Span"],
        desc=["Lagging Span — close price displaced backward (" + displace + ") for confirmation"]
    )
}

// --- Price Regime Fill (subtle background color by cloud position) ---
if (showPriceRegime) {
    var regimeColor = priceAboveCloud ? opacity(upColor, 8) : (priceBelowCloud ? opacity(dnColor, 8) : opacity("#9e9e9e", 4))
    plotLine(
        value=[h, l],
        width=1,
        colors=[regimeColor, regimeColor],
        fill=true,
        label=["Regime Fill", "Regime Fill"],
        desc=["Price regime overlay: green=above cloud, red=below cloud, grey=inside cloud"]
    )
}

// --- TK Cross Shape Markers ---
if (showShapes) {
    if (tkCrossUp) {
        plotShape(
            value=tenkan,
            shape="triangleup",
            color=tkCrossBull,
            width=3,
            label=["TK Cross Bull"],
            desc=["Tenkan-sen crossed above Kijun-sen — bullish TK cross signal"]
        )
    }
    if (tkCrossDown) {
        plotShape(
            value=tenkan,
            shape="triangledown",
            color=tkCrossBear,
            width=3,
            label=["TK Cross Bear"],
            desc=["Tenkan-sen crossed below Kijun-sen — bearish TK cross signal"]
        )
    }
}

// --- Kumo Breakout Shape Markers (stronger signals) ---
if (showShapes) {
    if (kumoBreakUp) {
        plotShape(
            value=c,
            shape="diamond",
            color=tkCrossBull,
            width=4,
            label=["Kumo Break Up"],
            desc=["Price broke above the cloud — strong bullish Ichimoku signal"]
        )
    }
    if (kumoBreakDown) {
        plotShape(
            value=c,
            shape="diamond",
            color=tkCrossBear,
            width=4,
            label=["Kumo Break Down"],
            desc=["Price broke below the cloud — strong bearish Ichimoku signal"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only — summary of Ichimoku state)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = priceAboveCloud ? "ABOVE CLOUD (BULL)" : (priceBelowCloud ? "BELOW CLOUD (BEAR)" : "INSIDE CLOUD (NEUTRAL)")
    var regimeTextColor = priceAboveCloud ? upColor : (priceBelowCloud ? dnColor : "#9e9e9e")
    var cloudTrend = cloudBull ? "BULLISH" : "BEARISH"
    var tkPosition = tenkan > kijun ? "ABOVE KIJUN" : "BELOW KIJUN"

    plotTable(
        data=[
            ["SCF Ichimoku — Perfected", regimeText],
            ["Tenkan-sen", tenkan[0]],
            ["Kijun-sen", kijun[0]],
            ["Senkou A", senkouA[0]],
            ["Senkou B", senkouB[0]],
            ["Cloud Trend", cloudTrend],
            ["TK Position", tkPosition],
            ["TK Bull Crosses", tkCrossBullCount],
            ["TK Bear Crosses", tkCrossBearCount],
            ["Kumo Break Up", kumoBreakUpCount],
            ["Kumo Break Down", kumoBreakDownCount],
            ["Max Cloud Thickness", maxCloudThickness]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}