MM Flow
FlowScripts

Perfected FlowScript

gg_shot

GG Shot — Perfected Edition is indexed as 167_gg_shot.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

16.4 KB

Lines

530

Native Signal Candidates

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

6/6 guarded

GG Long

line 411:9

Trigger

(showShapes) && (longSignal)

Value

low - atr * 0.5

Deps

longSignal:var, showShapes:input

GG Short

line 422:9

Trigger

(showShapes) && (shortSignal)

Value

high + atr * 0.5

Deps

shortSignal:var, showShapes:input

Score Long

line 433:9

Trigger

(showShapes) && (scoreSignalLong && !longSignal)

Value

low - atr * 0.3

Deps

longSignal:var, scoreSignalLong:var, showShapes:input

Score Short

line 443:9

Trigger

(showShapes) && (scoreSignalShort && !shortSignal)

Value

high + atr * 0.3

Deps

scoreSignalShort:var, shortSignal:var, showShapes:input

RSI OS

line 454:9

Trigger

(showShapes) && (rsiOsExtreme)

Value

low

Deps

rsiOsExtreme:var, showShapes:input

RSI OB

line 464:9

Trigger

(showShapes) && (rsiObExtreme)

Value

high

Deps

rsiObExtreme:var, showShapes:input

167_gg_shot.flowscript

source path: kscripts/perfected/167_gg_shot.flowscript · sha256:48bc9512dad05b023cb0f9bcdd0d4085421622b9649973e99fc49f7a6a9197d1

hash verified
//@version=2
// ============================================================================
// GG Shot — Perfected Edition
// Author: O (@Offres Pour Vous) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #ggshot, #multifactor, #signal, #regime, #momentum, #zscore
//
// Production-quality multi-factor signal indicator combining EMA trend,
// RSI momentum, ATR volatility, and volume confirmation into a composite
// scoring system with regime detection, z-score normalization, and
// comprehensive shape-marker trigger visualization.
//
// Research papers underpinning this design:
//  1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns": moving average crossovers
//     and trading range breakouts as profitable signals. Journal of Finance.
//  2. Sullivan, Timmermann & White (1999), "Data-Snooping, Technical Trading
//     Rule Performance, and the Bootstrap": best rules may fail after
//     data-snooping adjustment. Supports multi-factor confirmation.
//  3. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI, ATR, and Parabolic SAR formulas. RSI = 100 − [100/(1+RS)].
//  4. Kaufman (1995), "Smarter Trading": KAMA and Efficiency Ratio (ER =
//     Change/Volatility). Supports adaptive smoothing and noise filtering.
//  5. Chande & Kroll (1994), "The New Technical Trader": CMO and VIDYA
//     adaptive momentum. CMO = (UpSum − DnSum)/(UpSum + DnSum).
//  6. Bollinger (2001), "Bollinger on Bollinger Bands": %B, Bandwidth,
//     Squeeze detection. %B = (Close − Lower)/(Upper − Lower).
//  7. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": momentum as premier cross-sectional anomaly.
//  8. Mandelbrot (1963/1982), "The Fractal Geometry of Nature": fractal
//     dimension and Hurst exponent for regime classification.
// ============================================================================

define(
    title="GG Shot — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Trend ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=9,
    label="Fast EMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Trend"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=21,
    label="Slow EMA Length",
    constraints={min: 2, max: 100, step: 1},
    group="Trend"
)

// --- Momentum ---
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",
    constraints={min: 50, max: 95, step: 1},
    group="Momentum"
)
var rsiOs = input(
    name="rsiOs",
    type="number",
    defaultValue=30,
    label="RSI Oversold",
    constraints={min: 5, max: 50, step: 1},
    group="Momentum"
)

// --- Volatility ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 2, max: 50, step: 1},
    group="Volatility"
)
var atrSLMult = input(
    name="atrSLMult",
    type="number",
    defaultValue=1.5,
    label="ATR Stop-Loss Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volatility"
)
var atrTPMult = input(
    name="atrTPMult",
    type="number",
    defaultValue=2.5,
    label="ATR Take-Profit Multiplier",
    constraints={min: 0.5, max: 10.0, step: 0.1},
    group="Volatility"
)

// --- Volume Confirmation ---
var useVolume = input(
    name="useVolume",
    type="boolean",
    defaultValue=true,
    label="Use Volume Confirmation",
    group="Volume Confirmation"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 50, step: 1},
    group="Volume Confirmation"
)

// --- Scoring ---
var scoreThreshold = input(
    name="scoreThreshold",
    type="number",
    defaultValue=2.0,
    label="Signal Score Threshold",
    constraints={min: 1, max: 5, step: 0.5},
    group="Scoring"
)
var zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=20,
    label="Score Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Scoring"
)

// --- Display ---
var showTrendLines = input(
    name="showTrendLines",
    type="boolean",
    defaultValue=true,
    label="Show EMA Trend Lines",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal Shapes",
    group="Display"
)
var showSLTP = input(
    name="showSLTP",
    type="boolean",
    defaultValue=true,
    label="Show SL/TP Levels",
    group="Display"
)
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Composite Score",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table",
    group="Display"
)
var lineWidth = input(
    name="lineWidth",
    type="number",
    defaultValue=2,
    label="Line Width",
    constraints={min: 1, max: 4, step: 1},
    group="Display"
)

// --- Colors ---
var longColor = input(
    name="longColor",
    type="color",
    defaultValue="#26a69a",
    label="Long Signal Color",
    group="Colors"
)
var shortColor = input(
    name="shortColor",
    type="color",
    defaultValue="#ef5350",
    label="Short Signal Color",
    group="Colors"
)
var slColor = input(
    name="slColor",
    type="color",
    defaultValue="#ff5252",
    label="Stop Loss Color",
    group="Colors"
)
var tpColor = input(
    name="tpColor",
    type="color",
    defaultValue="#00e676",
    label="Take Profit Color",
    group="Colors"
)
var scoreBullColor = input(
    name="scoreBullColor",
    type="color",
    defaultValue="#00e676",
    label="Score Bull Color",
    group="Colors"
)
var scoreBearColor = input(
    name="scoreBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Score Bear Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

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

if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(volume[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. INDIVIDUAL FACTOR COMPUTATION
// ---------------------------------------------------------------------------

// --- ATR (Wilder, 1978) ---
timeseries tr = math.max(high - low,
    math.max(math.abs(high - close[1]), math.abs(low - close[1])))
timeseries atr = rma(tr, atrLen)

// --- EMA Trend ---
timeseries emaFast = ema(close, fastLen)
timeseries emaSlow = ema(close, slowLen)
var emaBull = emaFast > emaSlow
var emaBear = emaFast < emaSlow

// --- RSI (Wilder, 1978) ---
timeseries change = close - close[1]
timeseries gain = change > 0 ? change : 0.0
timeseries loss = change < 0 ? -change : 0.0
timeseries avgGain = rma(gain, rsiLen)
timeseries avgLoss = rma(loss, rsiLen)
timeseries rs = avgGain / math.max(avgLoss, 0.0000001)
timeseries rsi = 100.0 - (100.0 / (1.0 + rs))

var rsiInBullZone = rsi > 50 && rsi < rsiOb
var rsiInBearZone = rsi < 50 && rsi > rsiOs
var rsiObExtreme = rsi >= rsiOb
var rsiOsExtreme = rsi <= rsiOs

// --- Volume Confirmation ---
timeseries volSma = sma(volume, volLookback)
timeseries volRatio = volSma > 0 ? volume / volSma : 1.0
var volAboveAvg = volRatio > 1.0

// ---------------------------------------------------------------------------
// 4. MULTI-FACTOR COMPOSITE SCORING
// ---------------------------------------------------------------------------
// Each factor contributes +1 (bullish), -1 (bearish), or 0 (neutral).
// Factors: EMA trend (±1), RSI zone (±1), RSI extreme (±1), Volume (±1).
// Score range: -4 to +4. Threshold at ±2 for signal trigger.

var emaScore = emaBull ? 1 : (emaBear ? -1 : 0)
var rsiScore = rsiInBullZone ? 1 : (rsiInBearZone ? -1 : 0)
var rsiExtremeScore = rsiObExtreme ? -1 : (rsiOsExtreme ? 1 : 0)
var volScore = (useVolume && volAboveAvg) ? (emaBull ? 1 : (emaBear ? -1 : 0)) : 0

timeseries compositeScore = emaScore + rsiScore + rsiExtremeScore + volScore

// Z-score of composite score (standardized across lookback)
timeseries scoreMean = sma(compositeScore, zScoreLen)
timeseries scoreStd = stddev(compositeScore, zScoreLen)
timeseries scoreZ = scoreStd > 0 ? (compositeScore - scoreMean) / scoreStd : 0

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on composite score and trend alignment:
//   Trending Bull: compositeScore >= scoreThreshold AND emaBull
//   Trending Bear: compositeScore <= -scoreThreshold AND emaBear
//   Neutral: everything else (chop zone, mixed signals)

var regimeTrendBull = compositeScore >= scoreThreshold && emaBull
var regimeTrendBear = compositeScore <= -scoreThreshold && emaBear
var regimeNeutral = !regimeTrendBull && !regimeTrendBear

var regimeColor = regimeTrendBull ? longColor : (regimeTrendBear ? shortColor : neutralColor)

// ---------------------------------------------------------------------------
// 6. ENTRY SIGNALS (multi-factor confirmed)
// ---------------------------------------------------------------------------
// Long signal: EMA cross up + RSI in bull zone + volume above avg + score >= threshold
// Short signal: EMA cross down + RSI in bear zone + volume above avg + score <= -threshold

var emaCrossUp = emaFast > emaSlow && emaFast[1] <= emaSlow[1]
var emaCrossDown = emaFast < emaSlow && emaFast[1] >= emaSlow[1]

var longSignal = emaCrossUp && rsiInBullZone && (!useVolume || volAboveAvg) && compositeScore >= scoreThreshold
var shortSignal = emaCrossDown && rsiInBearZone && (!useVolume || volAboveAvg) && compositeScore <= -scoreThreshold

// Alternative: score-based signals (trigger when z-score crosses threshold)
var scoreSignalLong = scoreZ > 1.5 && scoreZ[1] <= 1.5
var scoreSignalShort = scoreZ < -1.5 && scoreZ[1] >= -1.5

// --- SL/TP LEVELS (ATR-based) ---
var longSL = close - atr * atrSLMult
var longTP = close + atr * atrTPMult
var shortSL = close + atr * atrSLMult
var shortTP = close - atr * atrTPMult

// ---------------------------------------------------------------------------
// 7. STATIC TRACKING (stateful signal tracking)
// ---------------------------------------------------------------------------
static lastLongSignalBar = -1
static lastShortSignalBar = -1
static longSignalCount = 0
static shortSignalCount = 0

if (lastLongSignalBar < 0) {
    lastLongSignalBar = 0
    lastShortSignalBar = 0
    longSignalCount = 0
    shortSignalCount = 0
}

if (longSignal) {
    longSignalCount = longSignalCount + 1
    lastLongSignalBar = 0
} else {
    lastLongSignalBar = lastLongSignalBar + 1
}

if (shortSignal) {
    shortSignalCount = shortSignalCount + 1
    lastShortSignalBar = 0
} else {
    lastShortSignalBar = lastShortSignalBar + 1
}

// ---------------------------------------------------------------------------
// 8. PLOTTING
// ---------------------------------------------------------------------------

// --- EMA Trend Lines (regime-colored fast, slow) ---
if (showTrendLines) {
    plotLine(
        value=[emaFast, emaSlow],
        width=lineWidth,
        colors=[regimeColor, neutralColor],
        colorIndex=emaBull ? 0 : 1,
        label=["EMA Fast", "EMA Slow"],
        desc=["Fast EMA (" + fastLen + ") — regime-colored", "Slow EMA (" + slowLen + ")"]
    )
}

// --- Composite Score (oscillator) ---
if (showScore) {
    plotLine(
        value=compositeScore,
        width=2,
        colors=[scoreBullColor, scoreBearColor, neutralColor],
        colorIndex=compositeScore > 0 ? 0 : (compositeScore < 0 ? 1 : 2),
        label=["GG Score"],
        desc=["Multi-factor composite score (EMA + RSI + Volume + RSI extreme)"]
    )
    // Reference lines
    hline(value=scoreThreshold, color=transparency(longColor, 50), width=1)
    hline(value=-scoreThreshold, color=transparency(shortColor, 50), width=1)
    hline(value=0, color="#ffffff20", width=1)
}

// --- Signal Shapes ---
if (showShapes) {
    // Long entry signal
    if (longSignal) {
        plotShape(
            value=low - atr * 0.5,
            shape="triangleup",
            colorIndex=longColor,
            width=3,
            label=["GG Long"],
            desc=["Long signal: EMA cross up + RSI bull zone + volume + score >= " + scoreThreshold]
        )
    }
    // Short entry signal
    if (shortSignal) {
        plotShape(
            value=high + atr * 0.5,
            shape="triangledown",
            colorIndex=shortColor,
            width=3,
            label=["GG Short"],
            desc=["Short signal: EMA cross down + RSI bear zone + volume + score <= -" + scoreThreshold]
        )
    }
    // Score-based secondary signals (smaller markers)
    if (scoreSignalLong && !longSignal) {
        plotShape(
            value=low - atr * 0.3,
            shape="arrowup",
            colorIndex=scoreBullColor,
            width=2,
            label=["Score Long"],
            desc=["Score z-score long trigger (z > 1.5)"]
        )
    }
    if (scoreSignalShort && !shortSignal) {
        plotShape(
            value=high + atr * 0.3,
            shape="arrowdown",
            colorIndex=scoreBearColor,
            width=2,
            label=["Score Short"],
            desc=["Score z-score short trigger (z < -1.5)"]
        )
    }
    // RSI extreme markers
    if (rsiOsExtreme) {
        plotShape(
            value=low,
            shape="circle",
            colorIndex=longColor,
            width=2,
            label=["RSI OS"],
            desc=["RSI oversold (<= " + rsiOs + ") — potential bounce"]
        )
    }
    if (rsiObExtreme) {
        plotShape(
            value=high,
            shape="circle",
            colorIndex=shortColor,
            width=2,
            label=["RSI OB"],
            desc=["RSI overbought (>= " + rsiOb + ") — potential pullback"]
        )
    }
}

// --- SL/TP Level Lines (on signal only, or always if preferred) ---
if (showSLTP) {
    if (longSignal) {
        plotLine(
            value=[longSL, longTP],
            colors=[slColor, tpColor],
            width=1,
            label=["Long SL", "Long TP"],
            desc=["Long stop loss (ATR×" + atrSLMult + ")", "Long take profit (ATR×" + atrTPMult + ")"]
        )
    }
    if (shortSignal) {
        plotLine(
            value=[shortSL, shortTP],
            colors=[slColor, tpColor],
            width=1,
            label=["Short SL", "Short TP"],
            desc=["Short stop loss (ATR×" + atrSLMult + ")", "Short take profit (ATR×" + atrTPMult + ")"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeTrendBull ? "TRENDING BULL" : (regimeTrendBear ? "TRENDING BEAR" : "NEUTRAL")
    var regimeTextColor = regimeTrendBull ? longColor : (regimeTrendBear ? shortColor : neutralColor)

    plotTable(
        data=[
            ["GG Shot — Perfected", regimeText],
            ["EMA Fast", emaFast[0]],
            ["EMA Slow", emaSlow[0]],
            ["RSI", rsi[0]],
            ["ATR", atr[0]],
            ["Composite Score", compositeScore[0]],
            ["Score Z-Score", scoreZ[0]],
            ["Vol Ratio", volRatio[0]],
            ["Long Signals", longSignalCount],
            ["Short Signals", shortSignalCount]
        ],
        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
    )
}