MM Flow
FlowScripts

Perfected FlowScript

HTF Candles • [Leviathan]

HTF Candles Leviathan — Perfected Edition is indexed as 171_htf_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

13.4 KB

Lines

459

Native Signal Candidates

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

3/3 guarded

HTF Break Up

line 394:5

Trigger

(showBreakMarkers && breakUpEvent)

Value

hi

Deps

breakUpEvent:var, showBreakMarkers:input

HTF Break Down

line 404:5

Trigger

(showBreakMarkers && breakDnEvent)

Value

lo

Deps

breakDnEvent:var, showBreakMarkers:input

Unlabeled shape

line 419:5

Trigger

(isLastBar)

Value

hi

Deps

isLastBar:builtin

171_htf_candles_leviathan.flowscript

source path: kscripts/perfected/171_htf_candles_leviathan.flowscript · sha256:4389bdf6bdebe16a9e8d4f23e06354af96bec091e83796536d3402e737adccb4

hash verified
//@version=2
// ============================================================================
// HTF Candles Leviathan — Higher-Timeframe Candle Overlay & Projection
// Author: Leviathan (@Leviathan) — Perfected Edition
// Tags: CORE, #htf, #candle, #multi-timeframe, #projection, #marketstructure
//
// Production-grade higher-timeframe candle overlay with proper OHLC projection,
// HTF direction color coding, break-of-HTF markers, and stateful tracking.
// Simulates HTF bars via bar-counter modulo logic, projecting the last completed
// HTF candle forward as a reference zone.
//
// Academic foundations:
//  - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing" (AQR / NYU). Time-series momentum profitable across nearly all
//    asset classes since 1880. Multi-timeframe trend alignment is a key driver
//    of trend-following returns. Supports HTF analysis as a structural filter.
//  - Murphy (1999), "Technical Analysis of the Financial Markets" (NYIF).
//    Higher timeframes define major trends; lower timeframes provide entry
//    timing. The HTF candle overlay visualizes this hierarchical relationship.
//  - Peters (1994), "Fractal Market Analysis" (Wiley). Self-similarity across
//    scales; market stability depends on heterogeneous investment horizons.
//    Fractal dimension analysis confirms that price structure is scale-invariant.
//  - Zakamulin (2023), "Optimal Trend-Following with Transaction Costs" (IRFA).
//    Optimal trend-following under transaction costs resembles SMA crossover
//    rules. Validates multi-timeframe trend confirmation as an optimal strategy.
//  - Clare et al. (2013), "Trend Following, Stop Losses, and the Frequency of
//    Trading" (Cass Business School). The 10-month MA rule produced the highest
//    Sharpe ratio; simpler rules outperform complex ones. HTF alignment is robust.
// ============================================================================

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

// === USER INPUTS ===
// --- HTF Settings ---
var htf = input(
    name="htf",
    type="select",
    defaultValue="4h",
    label="Higher Timeframe",
    options=["1h","2h","4h","6h","12h","1D","3D","1W","2W","1M","3M","6M","1Y"],
    group="HTF Settings"
)
var basePeriod = input(
    name="basePeriod",
    type="select",
    defaultValue="5m",
    label="Chart Base Period",
    options=["1m","3m","5m","15m","30m","1h","2h","4h"],
    group="HTF Settings"
)
var showProjection = input(
    name="showProjection",
    type="boolean",
    defaultValue=true,
    label="Show HTF Projection Lines",
    group="HTF Settings"
)
var showCurrentForming = input(
    name="showCurrentForming",
    type="boolean",
    defaultValue=true,
    label="Show Current Forming HTF Candle",
    group="HTF Settings"
)
var showBreakMarkers = input(
    name="showBreakMarkers",
    type="boolean",
    defaultValue=true,
    label="Show HTF Break Markers",
    group="HTF Settings"
)
var showHtfCandle = input(
    name="showHtfCandle",
    type="boolean",
    defaultValue=true,
    label="Show HTF Candle Body",
    group="HTF Settings"
)
var showWicks = input(
    name="showWicks",
    type="boolean",
    defaultValue=true,
    label="Show HTF Wick Lines",
    group="HTF Settings"
)

// --- Display ---
var lineWidth = input(
    name="lineWidth",
    type="number",
    defaultValue=1,
    label="Line Width",
    constraints={min: 1, max: 5, step: 1},
    group="Display"
)
var candleWidth = input(
    name="candleWidth",
    type="number",
    defaultValue=2,
    label="Candle Body Width",
    constraints={min: 1, max: 10, step: 1},
    group="Display"
)
var projectionOpacity = input(
    name="projectionOpacity",
    type="number",
    defaultValue=60,
    label="Projection Opacity %",
    constraints={min: 10, max: 100, step: 5},
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish HTF Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish HTF Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral HTF Color",
    group="Colors"
)
var breakUpColor = input(
    name="breakUpColor",
    type="color",
    defaultValue="#00e676",
    label="Break-Up Marker Color",
    group="Colors"
)
var breakDnColor = input(
    name="breakDnColor",
    type="color",
    defaultValue="#ff5252",
    label="Break-Down Marker Color",
    group="Colors"
)

// === HTF MULTIPLIER (bars per HTF candle) ===
// Map base period to minutes
var baseMins = (basePeriod == "1m") ? 1
    : (basePeriod == "3m") ? 3
    : (basePeriod == "5m") ? 5
    : (basePeriod == "15m") ? 15
    : (basePeriod == "30m") ? 30
    : (basePeriod == "1h") ? 60
    : (basePeriod == "2h") ? 120
    : 240

// Map HTF to minutes
var htfMins = (htf == "1h") ? 60
    : (htf == "2h") ? 120
    : (htf == "4h") ? 240
    : (htf == "6h") ? 360
    : (htf == "12h") ? 720
    : (htf == "1D") ? 1440
    : (htf == "3D") ? 4320
    : (htf == "1W") ? 10080
    : (htf == "2W") ? 20160
    : (htf == "1M") ? 43200
    : (htf == "3M") ? 129600
    : (htf == "6M") ? 259200
    : 518400

var htfMult = math.max(1, math.round(htfMins / baseMins))

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries cl = bars.close
timeseries op = bars.open

// isnan guard on first use of external data
if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(op[0])) {
    return
}

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

// --- STATIC STATE: HTF Candle Tracking ---
// Current forming HTF candle
static htfOpenVal = 0.0
static htfHighVal = 0.0
static htfLowVal = 0.0
static htfCloseVal = 0.0
static htfBarIdx = 0  // 0-based index within current HTF bar

// Last completed HTF candle (projected forward)
static prevHtfOpen = 0.0
static prevHtfHigh = 0.0
static prevHtfLow = 0.0
static prevHtfClose = 0.0
static prevHtfDirection = 0  // 1 = bullish, -1 = bearish, 0 = neutral

// Previous HTF high/low for break detection
static prevHtfHigh_2 = 0.0
static prevHtfLow_2 = 0.0

// Break event flags
static breakUpBar = 0
static breakDnBar = 0

// --- STATE UPDATE (only on bar close) ---
if (!isLiveUpdate) {
    // New HTF candle starting
    if (htfBarIdx == 0) {
        htfOpenVal = op
        htfHighVal = hi
        htfLowVal = lo
    } else {
        // Update running high/low
        if (hi > htfHighVal) {
            htfHighVal = hi
        }
        if (lo < htfLowVal) {
            htfLowVal = lo
        }
    }
    htfCloseVal = cl
    htfBarIdx = htfBarIdx + 1

    // HTF candle complete
    if (htfBarIdx >= htfMult) {
        // Shift completed candle to prev
        prevHtfOpen = htfOpenVal
        prevHtfHigh = htfHighVal
        prevHtfLow = htfLowVal
        prevHtfClose = htfCloseVal

        // Determine direction
        if (prevHtfClose > prevHtfOpen) {
            prevHtfDirection = 1
        } else if (prevHtfClose < prevHtfOpen) {
            prevHtfDirection = -1
        } else {
            prevHtfDirection = 0
        }

        // Break detection: price breaks above previous HTF high or below previous HTF low
        if (prevHtfHigh_2 > 0 && hi > prevHtfHigh_2) {
            breakUpBar = barCount
        }
        if (prevHtfLow_2 > 0 && lo < prevHtfLow_2) {
            breakDnBar = barCount
        }

        // Shift for next iteration
        prevHtfHigh_2 = prevHtfHigh
        prevHtfLow_2 = prevHtfLow

        // Reset for new HTF candle
        htfBarIdx = 0
        htfOpenVal = op
        htfHighVal = hi
        htfLowVal = lo
    }
}

// === EVENT FLAGS FOR PLOTTING ===
var breakUpEvent = breakUpBar == barCount
var breakDnEvent = breakDnBar == barCount

// Regime color based on HTF direction
var htfColor = prevHtfDirection == 1 ? upColor : (prevHtfDirection == -1 ? dnColor : neutralColor)
var htfFillColor = opacity(htfColor, projectionOpacity)
var htfWickColor = opacity(htfColor, math.max(30, projectionOpacity - 20))

// Current forming direction
var formingDirection = 0
if (htfCloseVal > htfOpenVal) {
    formingDirection = 1
} else if (htfCloseVal < htfOpenVal) {
    formingDirection = -1
}
var formingColor = formingDirection == 1 ? upColor : (formingDirection == -1 ? dnColor : neutralColor)

// === PLOTS: LAST COMPLETED HTF CANDLE (projected forward) ===
// HTF High / Low as a zone with fill
if (showProjection && prevHtfHigh > 0 && prevHtfLow > 0) {
    plotLine(
        value=[prevHtfHigh, prevHtfLow],
        width=lineWidth,
        colors=[htfWickColor, htfWickColor],
        fill=htfFillColor,
        label=["HTF High", "HTF Low"],
        desc=["Higher-timeframe high (projected)", "Higher-timeframe low (projected)"]
    )

    // Wick lines (high and low)
    if (showWicks) {
        plotLine(
            value=prevHtfHigh,
            width=lineWidth,
            colors=[htfWickColor],
            label=["HTF High"],
            desc=["Higher-timeframe wick high"]
        )
        plotLine(
            value=prevHtfLow,
            width=lineWidth,
            colors=[htfWickColor],
            label=["HTF Low"],
            desc=["Higher-timeframe wick low"]
        )
    }
}

// HTF Open / Close as candle body
if (showHtfCandle && prevHtfOpen > 0 && prevHtfClose > 0) {
    // Body fill between open and close
    var bodyTop = math.max(prevHtfOpen, prevHtfClose)
    var bodyBot = math.min(prevHtfOpen, prevHtfClose)
    var bodyColor = prevHtfDirection == 1 ? upColor : dnColor
    var bodyFillColor = opacity(bodyColor, projectionOpacity)

    plotLine(
        value=[bodyTop, bodyBot],
        width=candleWidth,
        colors=[bodyColor, bodyColor],
        fill=bodyFillColor,
        label=["HTF Body Top", "HTF Body Bot"],
        desc=["Higher-timeframe candle body top", "Higher-timeframe candle body bottom"]
    )

    // Open line
    plotLine(
        value=prevHtfOpen,
        width=lineWidth,
        colors=[opacity(bodyColor, 70)],
        label=["HTF Open"],
        desc=["Higher-timeframe open price (projected)"]
    )

    // Close line
    plotLine(
        value=prevHtfClose,
        width=lineWidth,
        colors=[opacity(bodyColor, 90)],
        label=["HTF Close"],
        desc=["Higher-timeframe close price (projected)"]
    )
}

// === PLOTS: CURRENT FORMING HTF CANDLE (ghost/outline) ===
if (showCurrentForming && htfBarIdx > 0) {
    var ghostColor = opacity(formingColor, 25)
    var ghostTop = math.max(htfOpenVal, htfCloseVal)
    var ghostBot = math.min(htfOpenVal, htfCloseVal)

    // Forming high/low zone
    plotLine(
        value=[htfHighVal, htfLowVal],
        width=1,
        colors=[ghostColor, ghostColor],
        fill=opacity(formingColor, 10),
        label=["Forming HTF High", "Forming HTF Low"],
        desc=["Current forming HTF high", "Current forming HTF low"]
    )

    // Forming body
    plotLine(
        value=[ghostTop, ghostBot],
        width=1,
        colors=[ghostColor, ghostColor],
        fill=opacity(formingColor, 15),
        label=["Forming HTF Body", "Forming HTF Body"],
        desc=["Current forming HTF candle body (ghost)", "Current forming HTF candle body (ghost)"]
    )
}

// === PLOTS: BREAK MARKERS ===
if (showBreakMarkers && breakUpEvent) {
    plotShape(
        value=hi,
        shape="triangleup",
        colorIndex=breakUpColor,
        width=6,
        label=["HTF Break Up"],
        desc=["Price broke above the previous higher-timeframe high"]
    )
}
if (showBreakMarkers && breakDnEvent) {
    plotShape(
        value=lo,
        shape="triangledown",
        colorIndex=breakDnColor,
        width=6,
        label=["HTF Break Down"],
        desc=["Price broke below the previous higher-timeframe low"]
    )
}

// === HTF DIRECTION LABEL (last bar only) ===
if (isLastBar) {
    var dirLabel = prevHtfDirection == 1 ? "HTF BULLISH" : (prevHtfDirection == -1 ? "HTF BEARISH" : "HTF NEUTRAL")
    var dirLabelColor = prevHtfDirection == 1 ? upColor : (prevHtfDirection == -1 ? dnColor : neutralColor)

    plotPriceLabel(
        price=hi,
        text=dirLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=dirLabelColor,
        size=10,
        fontWeight=700
    )
}

// === HTF SUMMARY TABLE (last bar only) ===
if (isLastBar) {
    var progressPct = htfMult > 0 ? math.round((htfBarIdx / htfMult) * 100) : 0
    var formLabel = formingDirection == 1 ? "BULLISH" : (formingDirection == -1 ? "BEARISH" : "NEUTRAL")

    plotTable(
        data=[
            ["HTF Candles Leviathan", htf + " / " + basePeriod],
            ["HTF Direction", prevHtfDirection == 1 ? "BULLISH" : (prevHtfDirection == -1 ? "BEARISH" : "NEUTRAL")],
            ["HTF Open", prevHtfOpen],
            ["HTF High", prevHtfHigh],
            ["HTF Low", prevHtfLow],
            ["HTF Close", prevHtfClose],
            ["Forming Candle", formLabel],
            ["Forming Progress", progressPct + "%"]
        ],
        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
    )
}