MM Flow
FlowScripts

Perfected FlowScript

techhint

TechHint Pro — Multi-Factor Intraday Trading Indicator is indexed as 313_techhint.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.3 KB

Lines

497

Native Signal Candidates

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

3/3 guarded

BUY SIGNAL

line 435:9

Trigger

(showSignals) && (bullSignal)

Value

src

Deps

bullSignal:var, showSignals:input

SELL SIGNAL

line 445:9

Trigger

(showSignals) && (bearSignal)

Value

src

Deps

bearSignal:var, showSignals:input

Unlabeled shape

line 458:5

Trigger

(showRegime && isLastBar)

Value

hi

Deps

isLastBar:builtin, showRegime:input

313_techhint.flowscript

source path: kscripts/perfected/313_techhint.flowscript · sha256:24d05c486190bed63a0006b7068f8da37e92b5d9d11e1c661f514f7d0ba828b1

hash verified
//@version=2
// ============================================================================
// TechHint Pro — Multi-Factor Intraday Trading Indicator Perfected Edition
// Author: kScript Perfection Engineer
// Tags: CORE, #techhint, #multifactor, #regime, #momentum, #breakout, #score
//
// Production-grade multi-factor intraday indicator combining market structure
// (EMA ribbon), momentum (RSI), volatility regime (ATR), and breakout detection
// (Donchian) into a unified scoring system with color-coded regime detection,
// dynamic threshold adaptation, and comprehensive visual overlays.
//
// Academic foundations:
//  - Wilder (1978), "New Concepts in Technical Trading Systems": canonical RSI
//    publication. RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N) /
//    SMA(loss, N). Original smoothing period = 14. [^1]
//  - Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//    Losers": established momentum as a premier cross-sectional anomaly.
//    Validates RSI's momentum-measurement role. [^2]
//  - Ponnusamy & Manual (2016): experimental finding that RSI outperforms MACD
//    and Stochastic in signal reliability; multi-indicator confirmation
//    recommended. Underpins the multi-factor scoring architecture. [^3]
//  - Khand et al. (2019), "EMA, MACD, RSI and Momentum Trading Rules": EMA
//    and MOM variants showed substantial prognostic capability. After
//    transaction costs, EMA variants (1,50,1) remained profitable. [^4]
//  - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing": time-series momentum profitable since 1880 across global
//    markets. Validates trend-following EMA architecture. [^5]
//  - Kaufman (1995), "Smarter Trading": Efficiency Ratio = Change / Volatility.
//    ER ranges 0 (no direction) to 1 (perfect trend). Underpins adaptive
//    regime detection. [^6]
//  - Bollinger (2001), "Bollinger on Bollinger Bands": %B and statistical band
//    concepts. Volatility compression precedes expansion. [^7]
//  - Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//    autocorrelation at medium horizons; supports dynamic threshold adaptation. [^8]
// ============================================================================

define(
    title="TechHint Pro — Multi-Factor Intraday Trading Indicator",
    position="onchart",
    axis=false
)

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

// --- Market Structure (EMA) ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=21,
    label="Fast EMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="Market Structure"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=55,
    label="Slow EMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="Market Structure"
)
var trendColor = input(
    name="trendColor",
    type="color",
    defaultValue="#2962ff",
    label="Trend EMA Color",
    group="Market Structure"
)

// --- Momentum (RSI) ---
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum"
)
var rsiOb = input(
    name="rsiOb",
    type="number",
    defaultValue=70,
    label="RSI Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Momentum"
)
var rsiOs = input(
    name="rsiOs",
    type="number",
    defaultValue=30,
    label="RSI Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="Momentum"
)
var rsiColor = input(
    name="rsiColor",
    type="color",
    defaultValue="#26a69a",
    label="RSI Panel Color",
    group="Momentum"
)

// --- Breakout (Donchian) ---
var donchianLn = input(
    name="donchianLn",
    type="number",
    defaultValue=20,
    label="Donchian Length",
    constraints={min: 2, max: 100, step: 1},
    group="Breakout"
)
var breakoutColor = input(
    name="breakoutColor",
    type="color",
    defaultValue="#9c27b0",
    label="Breakout Band Color",
    group="Breakout"
)

// --- Volatility / Risk ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="Risk Management"
)
var atrSl = input(
    name="atrSl",
    type="number",
    defaultValue=1.5,
    label="Stop Loss (ATR mult)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Risk Management"
)
var atrTp = input(
    name="atrTp",
    type="number",
    defaultValue=2.5,
    label="Take Profit (ATR mult)",
    constraints={min: 0.5, max: 10.0, step: 0.1},
    group="Risk Management"
)

// --- Multi-Factor Scoring ---
var scoreThreshold = input(
    name="scoreThreshold",
    type="number",
    defaultValue=2.0,
    label="Signal Threshold (score)",
    constraints={min: 0.0, max: 5.0, step: 0.5},
    group="Scoring"
)
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Composite Score",
    group="Scoring"
)

// --- Display ---
var showEMA = input(
    name="showEMA",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon",
    group="Display"
)
var showDonchian = input(
    name="showDonchian",
    type="boolean",
    defaultValue=true,
    label="Show Donchian Bands",
    group="Display"
)
var showSLTP = input(
    name="showSLTP",
    type="boolean",
    defaultValue=true,
    label="Show SL / TP Zones",
    group="Display"
)
var showSignals = input(
    name="showSignals",
    type="boolean",
    defaultValue=true,
    label="Show Entry Signal Shapes",
    group="Display"
)
var showRegime = input(
    name="showRegime",
    type="boolean",
    defaultValue=true,
    label="Show Regime Label",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish 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 src = bars.close
timeseries hi = bars.high
timeseries lo = bars.low

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

// ---------------------------------------------------------------------------
// 3. CORE CALCULATIONS
// ---------------------------------------------------------------------------

// EMA Ribbon
timeseries fastEma = ema(src, fastLen)
timeseries slowEma = ema(src, slowLen)

// Trend bias from EMA crossover
timeseries trendBias = fastEma - slowEma

// RSI (Wilder canonical)
timeseries change = src - src[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = sma(gain, rsiLen)
timeseries avgLoss = sma(loss, rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiVal = 100 - (100 / (1 + rs))

// Donchian breakout channel
timeseries donHi = highest(hi, donchianLn)
timeseries donLo = lowest(lo, donchianLn)

// ATR-based risk management
timeseries rng = hi - lo
timeseries prevClose = isnan(src[1]) ? src : src[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 atrV = sma(trueRange, atrLen)

// ---------------------------------------------------------------------------
// 4. MULTI-FACTOR SCORING SYSTEM
// ---------------------------------------------------------------------------
// Each factor contributes +1 (bullish) or -1 (bearish) or 0 (neutral).
// Factors: Trend (EMA), Momentum (RSI), Breakout (Donchian), Volatility (ATR regime).

// Factor 1: Trend — fast > slow = +1, fast < slow = -1
var trendScore = trendBias > 0 ? 1 : (trendBias < 0 ? -1 : 0)

// Factor 2: Momentum — RSI > 50 = +1, RSI < 50 = -1; extreme OB/OS = +2/-2
var momentumScore = 0
if (rsiVal > rsiOb) {
    momentumScore = 2
} else if (rsiVal > 50) {
    momentumScore = 1
} else if (rsiVal < rsiOs) {
    momentumScore = -2
} else if (rsiVal < 50) {
    momentumScore = -1
}

// Factor 3: Breakout — close above Donchian high = +1, below Donchian low = -1
var breakoutScore = 0
if (src > donHi[1]) {
    breakoutScore = 1
} else if (src < donLo[1]) {
    breakoutScore = -1
}

// Factor 4: Volatility regime — ATR expansion vs compression
// Compare ATR to its own SMA to detect expansion (trend) or compression (chop)
timeseries atrSma = sma(atrV, atrLen * 2)
var volScore = atrV > atrSma ? (trendScore > 0 ? 1 : (trendScore < 0 ? -1 : 0)) : 0

// Composite score: sum of all factors
var compositeScore = trendScore + momentumScore + breakoutScore + volScore

// Score normalization: clamp to [-5, 5] then map to z-like [-2.5, 2.5]
var scoreNorm = compositeScore
if (scoreNorm > 5) {
    scoreNorm = 5
}
if (scoreNorm < -5) {
    scoreNorm = -5
}

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on composite score:
//   Strong Bull: score >=  threshold
//   Strong Bear: score <= -threshold
//   Neutral: everything else (chop / mixed signals)

var regimeBull = compositeScore >= scoreThreshold
var regimeBear = compositeScore <= -scoreThreshold
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
var regimeLabel = regimeBull ? "STRONG BULL" : (regimeBear ? "STRONG BEAR" : "NEUTRAL / CHOP")

// ---------------------------------------------------------------------------
// 6. STATIC STATE: SIGNAL TRACKING
// ---------------------------------------------------------------------------
static lastSignalBar = 0
static lastSignalType = 0  // 1 = bull, -1 = bear

var bullSignal = false
var bearSignal = false

if (!isLiveUpdate) {
    // Bull signal: regime turns bullish, or score crosses up through threshold
    if (compositeScore >= scoreThreshold && lastSignalType != 1) {
        bullSignal = true
        lastSignalBar = barCount
        lastSignalType = 1
    }
    // Bear signal: regime turns bearish, or score crosses down through threshold
    if (compositeScore <= -scoreThreshold && lastSignalType != -1) {
        bearSignal = true
        lastSignalBar = barCount
        lastSignalType = -1
    }
    // Reset if back to neutral
    if (regimeNeutral && lastSignalType != 0) {
        lastSignalType = 0
    }
}

// ---------------------------------------------------------------------------
// 7. PLOTTING
// ---------------------------------------------------------------------------

// --- EMA Ribbon (fast/slow fill) ---
if (showEMA) {
    var ribbonBull = fastEma > slowEma
    plotLine(
        value=[fastEma, slowEma],
        width=2,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast EMA", "Slow EMA"],
        desc=["Fast EMA (" + fastLen + ") — short-term market structure", "Slow EMA (" + slowLen + ") — long-term market structure"]
    )
    // Individual EMA lines with regime coloring
    plotLine(
        value=fastEma,
        width=2,
        colors=[bullColor],
        label=["Fast EMA"],
        desc=["Fast EMA — short-term trend direction"]
    )
    plotLine(
        value=slowEma,
        width=2,
        colors=[bearColor],
        label=["Slow EMA"],
        desc=["Slow EMA — long-term trend direction"]
    )
}

// --- Donchian Breakout Bands ---
if (showDonchian) {
    plotLine(
        value=[donLo, donHi],
        width=1,
        colors=[transparency(breakoutColor, 40), transparency(breakoutColor, 40)],
        fill=transparency(breakoutColor, 15),
        label=["Donchian Low", "Donchian High"],
        desc=["Lower Donchian breakout level (" + donchianLn + ")", "Upper Donchian breakout level (" + donchianLn + ")"]
    )
}

// --- SL / TP Zones (ATR-based) ---
if (showSLTP) {
    timeseries slPx = src - atrV * atrSl
    timeseries tpPx = src + atrV * atrTp
    plotLine(
        value=[slPx, tpPx],
        width=1,
        colors=[transparency(bearColor, 40), transparency(bullColor, 40)],
        fill=transparency(neutralColor, 10),
        label=["Stop Loss", "Take Profit"],
        desc=["ATR-based stop loss (" + atrSl + "×ATR)", "ATR-based take profit (" + atrTp + "×ATR)"]
    )
}

// --- Composite Score (histogram-style bar) ---
if (showScore) {
    var scoreColor = compositeScore >= 0 ? bullColor : bearColor
    plotBar(
        value=compositeScore,
        colors=[transparency(scoreColor, 60)],
        label=["Composite Score"],
        desc=["Multi-factor score: Trend(" + trendScore + ") + Momentum(" + momentumScore + ") + Breakout(" + breakoutScore + ") + Volatility(" + volScore + ") = " + compositeScore]
    )
    hline(value=scoreThreshold, color=transparency(bullColor, 40), width=1)
    hline(value=-scoreThreshold, color=transparency(bearColor, 40), width=1)
    hline(value=0, color="#ffffff20", width=1)
}

// --- Entry Signal Shapes ---
if (showSignals) {
    if (bullSignal) {
        plotShape(
            value=src,
            shape="triangleup",
            colorIndex=bullColor,
            width=6,
            label=["BUY SIGNAL"],
            desc=["Multi-factor bullish confirmation: score = " + compositeScore + ". Trend + Momentum + Breakout aligned."]
        )
    }
    if (bearSignal) {
        plotShape(
            value=src,
            shape="triangledown",
            colorIndex=bearColor,
            width=6,
            label=["SELL SIGNAL"],
            desc=["Multi-factor bearish confirmation: score = " + compositeScore + ". Trend + Momentum + Breakout aligned."]
        )
    }
}

// --- Regime Label (last bar only) ---
if (showRegime && isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// --- Info Table (last bar only) ---
if (isLastBar) {
    var rsiText = rsiVal > rsiOb ? "OVERBOUGHT" : (rsiVal < rsiOs ? "OVERSOLD" : "NEUTRAL")
    var rsiTextColor = rsiVal > rsiOb ? bearColor : (rsiVal < rsiOs ? bullColor : neutralColor)

    plotTable(
        data=[
            ["TechHint Pro", regimeLabel],
            ["Composite Score", compositeScore],
            ["Trend", trendScore > 0 ? "BULL" : (trendScore < 0 ? "BEAR" : "NEUTRAL")],
            ["Momentum", rsiText],
            ["RSI", rsiVal],
            ["Breakout", breakoutScore > 0 ? "UP" : (breakoutScore < 0 ? "DOWN" : "NONE")],
            ["ATR", atrV]
        ],
        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
    )
}