MM Flow
FlowScripts

Perfected FlowScript

Heikin Ashi Candles • [Leviathan]

Heikin Ashi Candles • Leviathan — Perfected Edition is indexed as 237_heikin_ashi_candles_leviathan.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

15.6 KB

Lines

473

Native Signal Candidates

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

5/5 guarded

Strong Bull HA

line 374:5

Trigger

(showStrongBull && isStrongBull)

Value

haLow

Deps

isStrongBull:var, showStrongBull:input

Strong Bear HA

line 386:5

Trigger

(showStrongBear && isStrongBear)

Value

haHigh

Deps

isStrongBear:var, showStrongBear:input

HA Doji

line 398:5

Trigger

(showDojiMarkers && isDoji)

Value

(haHigh + haLow) / 2.0

Deps

isDoji:var, showDojiMarkers:input

Unlabeled shape

line 413:5

Trigger

(showTrendChange && trendChanged && barCount == trendBar)

Value

trend == 1 ? haLow : (trend == -1 ? haHigh : (haHigh + haLow) / 2.0)

Deps

barCount:static, showTrendChange:input, trendBar:static, trendChanged:var

Unlabeled shape

line 427:5

Trigger

(showTrendLabel && isLastBar)

Value

haHigh

Deps

isLastBar:builtin, showTrendLabel:input

237_heikin_ashi_candles_leviathan.flowscript

source path: kscripts/perfected/237_heikin_ashi_candles_leviathan.flowscript · sha256:fa04d918eee163fc7226eaa6c4882d7f30459a5eb6f846404a84738dcbabb5d8

hash verified
//@version=2
// ============================================================================
// Heikin Ashi Candles • Leviathan — Perfected Edition
// Author: Leviathan (@Leviathan) — Enhanced by kScript Perfection Engineer
// Tags: CORE, #heikin, #ashi, #heikinashi, #heikinashicandles, #trend, #momentum
//
// Production-grade Heikin-Ashi candle overlay with trend detection, strength
// classification, doji identification, regime-aware color coding, and shape
// markers for trend-change events. Stateful HA open tracking prevents NaN
// propagation on startup.
//
// Academic foundations:
//  - CMT Association / CFA Institute (2016), "Technical Analysis: Modern
//    Perspectives" (CFA Institute Research Foundation Literature Review, Vol. 11,
//    No. 11). Surveyed academic perspectives on smoothing techniques; notes that
//    Heikin-Ashi filtering reduces noise by modifying all four price points.
//    Key formula: HA-Close = (O+H+L+C)/4; HA-Open = (prev HA-O + prev HA-C)/2.
//  - Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability in
//    Technical Analysis" (European Academic Research). Found that no single
//    indicator is fully reliable; combining indicators and smoothing improves
//    performance. Heikin-Ashi noise reduction addresses the "erratic movement"
//    problem identified in this study.
//  - Wilder, J. W. Jr. (1978), "New Concepts in Technical Trading Systems"
//    (Trend Research). Mathematically rigorous smoothing established the precedent
//    for noise reduction in technical indicators (RSI, ATR, ADX). Heikin-Ashi
//    applies a similar smoothing philosophy to candlestick construction.
//  - Kaufman (1995), "Smarter Trading: Improving Performance in Changing Markets"
//    (McGraw-Hill). Introduced adaptive smoothing via Efficiency Ratio; the
//    trend-strength classification in this script uses a similar noise-to-signal
//    ratio approach for candle body dominance.
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J. Financial
//    Markets, 699+ citations). Framework: latent demands D(p) → realized prices via
//    λ·ΣX_i. HA smoothing reduces microstructure noise (λ effects) to reveal
//    latent demand trends.
// ============================================================================

define(
    title="Heikin Ashi Candles • Leviathan — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Heikin-Ashi Display ---
var showHA = input(
    name="showHA",
    type="boolean",
    defaultValue=true,
    label="Show Heikin-Ashi Candles",
    group="Heikin-Ashi Display"
)
var showOrig = input(
    name="showOrig",
    type="boolean",
    defaultValue=false,
    label="Show Original Candles",
    group="Heikin-Ashi Display"
)
var candleWidth = input(
    name="candleWidth",
    type="number",
    defaultValue=1,
    label="HA Candle Width",
    constraints={min: 1, max: 4, step: 1},
    group="Heikin-Ashi Display"
)

// --- Trend Detection ---
var trendLookback = input(
    name="trendLookback",
    type="number",
    defaultValue=5,
    label="Trend Lookback (bars)",
    constraints={min: 2, max: 50, step: 1},
    group="Trend Detection"
)
var strongBodyThreshold = input(
    name="strongBodyThreshold",
    type="number",
    defaultValue=0.7,
    label="Strong Body Threshold (body/range)",
    constraints={min: 0.3, max: 1.0, step: 0.05},
    group="Trend Detection"
)
var dojiThreshold = input(
    name="dojiThreshold",
    type="number",
    defaultValue=0.1,
    label="Doji Threshold (body/range)",
    constraints={min: 0.0, max: 0.3, step: 0.05},
    group="Trend Detection"
)
var showTrendLabel = input(
    name="showTrendLabel",
    type="boolean",
    defaultValue=true,
    label="Show Trend State Label",
    group="Trend Detection"
)

// --- Shape Markers ---
var showStrongBull = input(
    name="showStrongBull",
    type="boolean",
    defaultValue=true,
    label="Show Strong Bullish Markers",
    group="Shape Markers"
)
var showStrongBear = input(
    name="showStrongBear",
    type="boolean",
    defaultValue=true,
    label="Show Strong Bearish Markers",
    group="Shape Markers"
)
var showDojiMarkers = input(
    name="showDojiMarkers",
    type="boolean",
    defaultValue=true,
    label="Show Doji Markers",
    group="Shape Markers"
)
var showTrendChange = input(
    name="showTrendChange",
    type="boolean",
    defaultValue=true,
    label="Show Trend Change Markers",
    group="Shape Markers"
)

// --- Colors ---
var bullStrongColor = input(
    name="bullStrongColor",
    type="color",
    defaultValue="#00e676",
    label="Strong Bullish Color",
    group="Colors"
)
var bullWeakColor = input(
    name="bullWeakColor",
    type="color",
    defaultValue="#26a69a",
    label="Weak Bullish Color",
    group="Colors"
)
var bearStrongColor = input(
    name="bearStrongColor",
    type="color",
    defaultValue="#ff5252",
    label="Strong Bearish Color",
    group="Colors"
)
var bearWeakColor = input(
    name="bearWeakColor",
    type="color",
    defaultValue="#ef5350",
    label="Weak Bearish Color",
    group="Colors"
)
var dojiColor = input(
    name="dojiColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Doji Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#888888",
    label="Original Candle Color",
    group="Colors"
)
var trendUpColor = input(
    name="trendUpColor",
    type="color",
    defaultValue="#26a69a",
    label="Trend Up Label Color",
    group="Colors"
)
var trendDownColor = input(
    name="trendDownColor",
    type="color",
    defaultValue="#ef5350",
    label="Trend Down Label Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries open = ohlcvTS.open
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries close = ohlcvTS.close

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(open[0])) {
    return
}

// ------------------------------------------------------------------------------
// 3. HEIKIN-ASHI COMPUTATION
// ------------------------------------------------------------------------------
// Heikin Ashi Close = (O + H + L + C) / 4
// Heikin Ashi Open = (prev HA Open + prev HA Close) / 2
// HA High = max(H, HA Open, HA Close)
// HA Low = min(L, HA Open, HA Close)
//
// Per CMT Association (2016) and Wilder (1978) smoothing philosophy.

timeseries haClose = (open + high + low + close) / 4.0

// Stateful HA open to prevent NaN propagation on first bars
static haOpenState = na
if (isnan(haOpenState)) {
    haOpenState = (open[0] + close[0]) / 2.0
}
// HA open on this bar: (prev HA open + prev HA close) / 2
timeseries haOpen = (haOpenState[1] + haClose[1]) / 2.0
// If previous bar was NaN (startup), fall back to current bar midpoint
if (isnan(haOpen)) {
    haOpen = (open[0] + close[0]) / 2.0
}
haOpenState = haOpen

// HA High and Low
timeseries haHigh = math.max(high, math.max(haOpen, haClose))
timeseries haLow = math.min(low, math.min(haOpen, haClose))

// Build HA OHLC struct
timeseries haOHLC = [haOpen, haHigh, haLow, haClose]

// ------------------------------------------------------------------------------
// 4. CANDLE ANALYSIS — body, wicks, range, strength
// ------------------------------------------------------------------------------
timeseries haBody = math.abs(haClose - haOpen)
timeseries haRange = haHigh - haLow

// Body-to-range ratio (0 = doji, 1 = full body)
timeseries bodyRatio = haRange > 0 ? haBody / haRange : 0.0

// Upper and lower wicks
timeseries upperWick = haHigh - math.max(haOpen, haClose)
timeseries lowerWick = math.min(haOpen, haClose) - haLow

// Wick dominance ratios
timeseries upperWickRatio = haRange > 0 ? upperWick / haRange : 0.0
timeseries lowerWickRatio = haRange > 0 ? lowerWick / haRange : 0.0

// Direction classification
var isBullish = haClose >= haOpen
var isBearish = haClose < haOpen
var isDoji = bodyRatio <= dojiThreshold && haRange > 0
var isStrongBull = isBullish && bodyRatio >= strongBodyThreshold
var isStrongBear = isBearish && bodyRatio >= strongBodyThreshold
var isWeakBull = isBullish && bodyRatio < strongBodyThreshold && !isDoji
var isWeakBear = isBearish && bodyRatio < strongBodyThreshold && !isDoji

// ------------------------------------------------------------------------------
// 5. TREND DETECTION (stateful via static)
// ------------------------------------------------------------------------------
// Trend state machine: 1 = uptrend, -1 = downtrend, 0 = neutral
// Uses a lookback of HA closes to determine directional bias.

static trend = 0
static prevTrend = 0
static trendBar = 0

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

// HA-based trend detection: count bullish vs bearish candles in lookback
var bullCount = 0
var bearCount = 0
for (i = 0; i < trendLookback; i = i + 1) {
    if (!isnan(haClose[i]) && !isnan(haOpen[i])) {
        if (haClose[i] >= haOpen[i]) {
            bullCount = bullCount + 1
        } else {
            bearCount = bearCount + 1
        }
    }
}

// Trend determination: majority rule with tie-breaker on most recent candle
var newTrend = trend
if (bullCount > bearCount) {
    newTrend = 1
} else if (bearCount > bullCount) {
    newTrend = -1
} else {
    // tie-breaker: use most recent candle direction
    if (isBullish) {
        newTrend = 1
    } else if (isBearish) {
        newTrend = -1
    } else {
        newTrend = 0
    }
}

// Detect trend change on bar close
var trendChanged = false
if (!isLiveUpdate) {
    prevTrend = trend
    if (newTrend != trend) {
        trendChanged = true
        trendBar = barCount
    }
    trend = newTrend
}

// Trend strength: ratio of consecutive same-direction candles in lookback
var trendStrength = 0.0
if (trendLookback > 0) {
    if (trend == 1) {
        trendStrength = bullCount / trendLookback
    } else if (trend == -1) {
        trendStrength = bearCount / trendLookback
    }
}

// ------------------------------------------------------------------------------
// 6. COLOR CLASSIFICATION
// ------------------------------------------------------------------------------
// Color index mapping:
//   0 = strong bull, 1 = weak bull, 2 = doji, 3 = weak bear, 4 = strong bear
var colorIdx = isStrongBull ? 0 : (isWeakBull ? 1 : (isDoji ? 2 : (isWeakBear ? 3 : 4)))
var candleColors = [bullStrongColor, bullWeakColor, dojiColor, bearWeakColor, bearStrongColor]

// Regime color for label
var regimeColor = trend == 1 ? trendUpColor : (trend == -1 ? trendDownColor : neutralColor)
var regimeLabel = trend == 1 ? "HA UPTREND" : (trend == -1 ? "HA DOWNTREND" : "HA NEUTRAL")

// ------------------------------------------------------------------------------
// 7. HA CANDLE PLOTS
// ------------------------------------------------------------------------------
if (showHA) {
    plotCandle(
        value=haOHLC,
        colors=candleColors,
        colorIndex=colorIdx,
        width=candleWidth,
        label=["HA Open", "HA High", "HA Low", "HA Close"],
        desc=["Heikin-Ashi open (smoothed)", "Heikin-Ashi high", "Heikin-Ashi low", "Heikin-Ashi close (O+H+L+C)/4"],
        forceOnChart=true
    )
}

if (showOrig) {
    plotCandle(
        value=ohlcvTS,
        colors=[neutralColor, neutralColor],
        width=1,
        label=["Orig O", "Orig H", "Orig L", "Orig C"],
        desc=["Original candlestick OHLC for context"],
        forceOnChart=true
    )
}

// ------------------------------------------------------------------------------
// 8. SHAPE MARKERS
// ------------------------------------------------------------------------------
// Strong bullish marker: large green triangle below low
if (showStrongBull && isStrongBull) {
    plotShape(
        value=haLow,
        shape="triangleup",
        colorIndex=bullStrongColor,
        width=4,
        label=["Strong Bull HA"],
        desc=["Strong bullish Heikin-Ashi candle: body/range >= " + strongBodyThreshold + ", minimal upper wick. Indicates strong buying pressure."]
    )
}

// Strong bearish marker: large red triangle above high
if (showStrongBear && isStrongBear) {
    plotShape(
        value=haHigh,
        shape="triangledown",
        colorIndex=bearStrongColor,
        width=4,
        label=["Strong Bear HA"],
        desc=["Strong bearish Heikin-Ashi candle: body/range >= " + strongBodyThreshold + ", minimal lower wick. Indicates strong selling pressure."]
    )
}

// Doji marker: diamond at midpoint
if (showDojiMarkers && isDoji) {
    plotShape(
        value=(haHigh + haLow) / 2.0,
        shape="diamond",
        colorIndex=dojiColor,
        width=3,
        label=["HA Doji"],
        desc=["Heikin-Ashi doji: body/range <= " + dojiThreshold + ". Indicates indecision or potential trend exhaustion."]
    )
}

// Trend change marker: cross at extreme
if (showTrendChange && trendChanged && barCount == trendBar) {
    var trendChangeColor = trend == 1 ? bullStrongColor : (trend == -1 ? bearStrongColor : dojiColor)
    var trendChangeShape = trend == 1 ? "triangleup" : (trend == -1 ? "triangledown" : "diamond")
    var trendChangeLabel = trend == 1 ? "HA Trend Up" : (trend == -1 ? "HA Trend Down" : "HA Trend Neutral")
    plotShape(
        value=trend == 1 ? haLow : (trend == -1 ? haHigh : (haHigh + haLow) / 2.0),
        shape=trendChangeShape,
        colorIndex=trendChangeColor,
        width=5,
        label=[trendChangeLabel],
        desc=["Heikin-Ashi trend change detected. " + bullCount + " bullish / " + bearCount + " bearish candles in " + trendLookback + "-bar lookback."]
    )
}

// ------------------------------------------------------------------------------
// 9. TREND LABEL (last bar only)
// ------------------------------------------------------------------------------
if (showTrendLabel && isLastBar) {
    plotPriceLabel(
        price=haHigh,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// ------------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var trendText = trend == 1 ? "UPTREND" : (trend == -1 ? "DOWNTREND" : "NEUTRAL")
    var trendTextColor = trend == 1 ? bullStrongColor : (trend == -1 ? bearStrongColor : dojiColor)
    var bodyPct = bodyRatio * 100
    var wickUpPct = upperWickRatio * 100
    var wickDownPct = lowerWickRatio * 100

    plotTable(
        data=[
            ["HA Candles • Leviathan", trendText],
            ["HA Close", haClose[0]],
            ["HA Open", haOpen[0]],
            ["HA High", haHigh[0]],
            ["HA Low", haLow[0]],
            ["Body/Range", bodyPct + "%"],
            ["Upper Wick", wickUpPct + "%"],
            ["Lower Wick", wickDownPct + "%"],
            ["Trend Strength", trendStrength * 100 + "%"]
        ],
        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
    )
}