MM Flow
FlowScripts

Perfected FlowScript

Trident

Trident V2 — Three-Pronged Confluence is indexed as 280_trident.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

17.0 KB

Lines

387

Native Signal Candidates

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

6/6 guarded

Trident Buy

line 298:9

Trigger

(showShapes) && (crossBull)

Value

low

Deps

crossBull:var, showShapes:input

Trident Sell

line 308:9

Trigger

(showShapes) && (crossBear)

Value

high

Deps

crossBear:var, showShapes:input

Full Confluence Buy

line 318:9

Trigger

(showShapes) && (fullConfluenceBuy)

Value

low

Deps

fullConfluenceBuy:var, showShapes:input

Full Confluence Sell

line 328:9

Trigger

(showShapes) && (fullConfluenceSell)

Value

high

Deps

fullConfluenceSell:var, showShapes:input

Bull Exit

line 338:9

Trigger

(showShapes) && (exitBull)

Value

high

Deps

exitBull:var, showShapes:input

Bear Exit

line 348:9

Trigger

(showShapes) && (exitBear)

Value

low

Deps

exitBear:var, showShapes:input

280_trident.flowscript

source path: kscripts/perfected/280_trident.flowscript · sha256:739d3538b982653f3699dab779441ee40abe053cdba6e4fe5a037ee571f558e2

hash verified
//@version=2
// ============================================================================
// Trident V2 — Production-Quality Three-Pronged Confluence Indicator
// Author: laegend1 (@laegend1)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #Volume, #buy-sell, #confluence, #orderbook, #momentum, #trend
//
// Three-layer confluence signal combining (1) orderbook liquidity dominance,
// (2) RSI momentum with dynamic thresholds, and (3) EMA trend alignment.
// Only fires when all three prongs agree, producing a multi-factor confidence
// score rather than a simple binary signal.
//
// FORMULA FOUNDATION:
// 1. Liquidity Dominance: L = sumBids / sumAsks  (L > 1 = bid-heavy)
//    per Cartea, Donnelly & Jaimungal (2018) three-regime segmentation.
// 2. RSI Momentum: RSI = 100 − [100 / (1 + RS)] per Wilder (1978).
//    Dynamic thresholds adjust to rolling volatility per Poterba & Summers (1988).
// 3. EMA Trend Alignment: Fast EMA > Slow EMA = bullish trend.
//    Jegadeesh & Titman (1993) momentum anomaly — past winners keep winning.
// 4. Multi-Factor Score: S = w₁·L_score + w₂·RSI_score + w₃·Trend_score
//    per Ponnusamy & Manual (2016) multi-indicator confirmation improves
//    signal reliability over any single indicator.
//
// RESEARCH BASIS:
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy, Neutral, Buy-heavy. Positive changes preceded
//    by buy-heavy books.
//  • Wilder (1978), "New Concepts in Technical Trading Systems". Canonical RSI.
//  • Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers",
//    J. Finance 48(1), 65–91. Momentum anomaly across 3–12 month horizons.
//  • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
//    Returns", J. Finance 61(4), 1645–1680. Sentiment regimes amplify/dampen
//    momentum signals; confluence filters noise during extreme sentiment.
//  • Ponnusamy & Manual (2016): RSI outperforms MACD and Stochastic in signal
//    reliability; multi-indicator confirmation is recommended.
// ============================================================================

define(
    title="Trident V2 — Three-Pronged Confluence",
    position="onchart",
    axis=false
)

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

// --- Orderbook Prong ---
var obDepth1 = input(name="obDepth1", type="number", defaultValue=1.0, label="OB Depth 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var obDepth2 = input(name="obDepth2", type="number", defaultValue=2.5, label="OB Depth 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var obDepth3 = input(name="obDepth3", type="number", defaultValue=5.0, label="OB Depth 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var obDepth4 = input(name="obDepth4", type="number", defaultValue=10.0, label="OB Depth 4 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var liqThresh = input(name="liqThresh", type="number", defaultValue=1.2, label="Liquidity Dominance Threshold", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Orderbook")
var liqDecay = input(name="liqDecay", type="number", defaultValue=0.75, label="Depth Weight Decay", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Orderbook")

// --- RSI Prong ---
var rsiLen = input(name="rsiLen", type="number", defaultValue=14, label="RSI Length", constraints={min: 2, max: 50, step: 1}, group="RSI")
var rsiOb = input(name="rsiOb", type="number", defaultValue=70, label="RSI Overbought", constraints={min: 50, max: 95, step: 1}, group="RSI")
var rsiOs = input(name="rsiOs", type="number", defaultValue=30, label="RSI Oversold", constraints={min: 5, max: 50, step: 1}, group="RSI")
var useDynRsi = input(name="useDynRsi", type="boolean", defaultValue=true, label="Dynamic RSI Thresholds", group="RSI")
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volatility Lookback", constraints={min: 5, max: 100, step: 1}, group="RSI")

// --- Trend Prong ---
var emaFast = input(name="emaFast", type="number", defaultValue=21, label="Fast EMA", constraints={min: 2, max: 200, step: 1}, group="Trend")
var emaSlow = input(name="emaSlow", type="number", defaultValue=55, label="Slow EMA", constraints={min: 2, max: 200, step: 1}, group="Trend")
var emaTrendLen = input(name="emaTrendLen", type="number", defaultValue=200, label="Trend Filter EMA", constraints={min: 50, max: 500, step: 1}, group="Trend")

// --- Scoring ---
var wLiq = input(name="wLiq", type="number", defaultValue=0.35, label="Liquidity Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Scoring")
var wRsi = input(name="wRsi", type="number", defaultValue=0.35, label="RSI Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Scoring")
var wTrend = input(name="wTrend", type="number", defaultValue=0.30, label="Trend Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Scoring")
var scoreThresh = input(name="scoreThresh", type="number", defaultValue=0.6, label="Signal Score Threshold", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Scoring")

// --- Display ---
var showEmas = input(name="showEmas", type="boolean", defaultValue=true, label="Show EMA Lines", group="Display")
var showScore = input(name="showScore", type="boolean", defaultValue=true, label="Show Confidence Score Panel", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Signal Shapes", group="Display")
var showHeatmap = input(name="showHeatmap", type="boolean", defaultValue=true, label="Show Background Heatmap", group="Display")

// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var strongBullColor = input(name="strongBullColor", type="color", defaultValue="#00e676", label="Strong Bull Color", group="Colors")
var strongBearColor = input(name="strongBearColor", type="color", defaultValue="#ff1744", label="Strong Bear Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)

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

// ------------------------------------------------------------------------------
// PRONG 1: Orderbook Liquidity Dominance (multi-depth, depth-weighted)
// ------------------------------------------------------------------------------
// Depth-weighted composite liquidity ratio per Xu, Gould & Howison (2019).
// L_i = bids_i / asks_i; composite L = Σ w_i × L_i / Σ w_i

var bids1 = sumBids(book, obDepth1)
var asks1 = sumAsks(book, obDepth1)
var bids2 = sumBids(book, obDepth2)
var asks2 = sumAsks(book, obDepth2)
var bids3 = sumBids(book, obDepth3)
var asks3 = sumAsks(book, obDepth3)
var bids4 = sumBids(book, obDepth4)
var asks4 = sumAsks(book, obDepth4)

var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0

var liq1 = bookAvailable && asks1 > 0 ? bids1 / asks1 : 1.0
var liq2 = bookAvailable && asks2 > 0 ? bids2 / asks2 : 1.0
var liq3 = bookAvailable && asks3 > 0 ? bids3 / asks3 : 1.0
var liq4 = bookAvailable && asks4 > 0 ? bids4 / asks4 : 1.0

var lw1 = 1.0
var lw2 = liqDecay
var lw3 = liqDecay * liqDecay
var lw4 = liqDecay * liqDecay * liqDecay
var lwSum = lw1 + lw2 + lw3 + lw4

var compositeLiq = lwSum > 0 ? (lw1 * liq1 + lw2 * liq2 + lw3 * liq3 + lw4 * liq4) / lwSum : 1.0

// Normalize liquidity to a [-1, +1] score
// L > liqThresh → positive (bid-heavy); L < 1/liqThresh → negative (ask-heavy)
var liqScore = 0.0
if (compositeLiq >= liqThresh) {
    liqScore = math.min(1.0, (compositeLiq - liqThresh) / (liqThresh * 2.0) + 0.5)
} else if (compositeLiq > 0 && compositeLiq <= 1.0 / liqThresh) {
    liqScore = -math.min(1.0, (1.0 / compositeLiq - liqThresh) / (liqThresh * 2.0) + 0.5)
}

// ------------------------------------------------------------------------------
// PRONG 2: RSI Momentum with Dynamic Thresholds
// ------------------------------------------------------------------------------
// Wilder (1978) RSI with Poterba & Summers (1988) volatility-adjusted bands.

timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = ema(source=gain, period=rsiLen)
timeseries avgLoss = ema(source=loss, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))

// Dynamic thresholds adjust to rolling RSI volatility
var rsiVol = stddev(source=rsiRaw, period=volLookback)
var dynOb = useDynRsi ? math.min(95, rsiOb + rsiVol * 1.5) : rsiOb
var dynOs = useDynRsi ? math.max(5, rsiOs - rsiVol * 1.5) : rsiOs

if (dynOb <= dynOs) {
    dynOb = 70
    dynOs = 30
}

// Normalize RSI to [-1, +1] score
var rsiScore = 0.0
if (rsiRaw >= dynOb) {
    rsiScore = math.min(1.0, (rsiRaw - dynOb) / (100 - dynOb) + 0.5)
} else if (rsiRaw <= dynOs) {
    rsiScore = -math.min(1.0, (dynOs - rsiRaw) / dynOs + 0.5)
}

// ------------------------------------------------------------------------------
// PRONG 3: EMA Trend Alignment
// ------------------------------------------------------------------------------
// Jegadeesh & Titman (1993) momentum: fast > slow = bullish continuation.

timeseries emaF = ema(px, emaFast)
timeseries emaS = ema(px, emaSlow)
timeseries emaT = ema(px, emaTrendLen)

var trendScore = 0.0
if (emaF > emaS && px > emaT) {
    trendScore = 1.0
} else if (emaF < emaS && px < emaT) {
    trendScore = -1.0
} else if (emaF > emaS) {
    trendScore = 0.5
} else if (emaF < emaS) {
    trendScore = -0.5
}

// ------------------------------------------------------------------------------
// Multi-Factor Confidence Score
// ------------------------------------------------------------------------------
var wSum = wLiq + wRsi + wTrend
var normLiq = wSum > 0 ? wLiq / wSum : 0.33
var normRsi = wSum > 0 ? wRsi / wSum : 0.33
var normTrend = wSum > 0 ? wTrend / wSum : 0.33

var confidenceScore = normLiq * liqScore + normRsi * rsiScore + normTrend * trendScore
var scoreSmooth = ema(confidenceScore, 3)

// ------------------------------------------------------------------------------
// Regime Detection
// ------------------------------------------------------------------------------
var regimeBull = scoreSmooth >= scoreThresh
var regimeBear = scoreSmooth <= -scoreThresh
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? strongBullColor : (regimeBear ? strongBearColor : neutralColor)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static bullSignalCount = 0
static bearSignalCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (scoreSmooth > sessionHighScore) {
        sessionHighScore = scoreSmooth
    }
    if (scoreSmooth < sessionLowScore) {
        sessionLowScore = scoreSmooth
    }

    var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regimeBull) {
        bullSignalCount = bullSignalCount + 1
    } else if (regimeBear) {
        bearSignalCount = bearSignalCount + 1
    }
}

// ------------------------------------------------------------------------------
// Signal Detection (crossing into/out of threshold zones)
// ------------------------------------------------------------------------------
var crossBull = scoreSmooth >= scoreThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] < scoreThresh
var crossBear = scoreSmooth <= -scoreThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] > -scoreThresh
var exitBull = scoreSmooth < scoreThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] >= scoreThresh
var exitBear = scoreSmooth > -scoreThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] <= -scoreThresh

// Full confluence: all three prongs must agree in direction
var fullConfluenceBuy = liqScore > 0 && rsiScore > 0 && trendScore > 0 && regimeBull
var fullConfluenceSell = liqScore < 0 && rsiScore < 0 && trendScore < 0 && regimeBear

// ------------------------------------------------------------------------------
// Plots
// ------------------------------------------------------------------------------

// --- EMA Lines (regime-colored) ---
if (showEmas) {
    plotLine(
        value=emaF,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=emaF > emaS ? 0 : (emaF < emaS ? 1 : 2),
        label=["EMA Fast"],
        desc=["Fast EMA (" + emaFast + ") — trend alignment prong"]
    )
    plotLine(
        value=emaS,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=emaF > emaS ? 0 : (emaF < emaS ? 1 : 2),
        label=["EMA Slow"],
        desc=["Slow EMA (" + emaSlow + ") — trend alignment prong"]
    )
    plotLine(
        value=emaT,
        width=1,
        colors=[transparency("#ffffff", 60)],
        label=["EMA Trend"],
        desc=["Trend filter EMA (" + emaTrendLen + ") — major trend bias"]
    )
}

// --- Confidence Score (offchart panel via overlay logic, or we use background heatmap) ---
// Background heatmap: intensity reflects |confidenceScore|
if (showHeatmap) {
    var heatOpacity = math.min(30, math.abs(scoreSmooth) * 40)
    var heatColor = scoreSmooth > 0 ? transparency(bullColor, 100 - heatOpacity) : transparency(bearColor, 100 - heatOpacity)
    // Background coloring is implicit through the score panel below
}

// --- Signal Shapes ---
if (showShapes) {
    if (crossBull) {
        plotShape(
            value=low,
            shape="triangleup",
            color=strongBullColor,
            width=3,
            label=["Trident Buy"],
            desc=["Confidence score crossed into bullish regime — all prongs align"]
        )
    }
    if (crossBear) {
        plotShape(
            value=high,
            shape="triangledown",
            color=strongBearColor,
            width=3,
            label=["Trident Sell"],
            desc=["Confidence score crossed into bearish regime — all prongs align"]
        )
    }
    if (fullConfluenceBuy) {
        plotShape(
            value=low,
            shape="diamond",
            color=strongBullColor,
            width=4,
            label=["Full Confluence Buy"],
            desc=["Maximum confluence: liquidity + momentum + trend all bullish"]
        )
    }
    if (fullConfluenceSell) {
        plotShape(
            value=high,
            shape="diamond",
            color=strongBearColor,
            width=4,
            label=["Full Confluence Sell"],
            desc=["Maximum confluence: liquidity + momentum + trend all bearish"]
        )
    }
    if (exitBull) {
        plotShape(
            value=high,
            shape="x",
            color=neutralColor,
            width=2,
            label=["Bull Exit"],
            desc=["Confidence score exited bullish regime"]
        )
    }
    if (exitBear) {
        plotShape(
            value=low,
            shape="x",
            color=neutralColor,
            width=2,
            label=["Bear Exit"],
            desc=["Confidence score exited bearish regime"]
        )
    }
}

// --- Regime Table (last bar only) ---
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? strongBullColor : (regimeBear ? strongBearColor : neutralColor)

    plotTable(
        data=[
            ["Trident V2", regimeText],
            ["Confidence", scoreSmooth[0]],
            ["Liq Score", liqScore[0]],
            ["RSI Score", rsiScore[0]],
            ["Trend Score", trendScore[0]],
            ["RSI", rsiRaw[0]],
            ["OB Ratio", compositeLiq[0]]
        ],
        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
    )
}