Perfected FlowScript
Close price
Close Price Pro — Perfected Edition is indexed as 297_close_price.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
12.8 KB
Lines
425
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
MA Cross Up
line 352:9
Trigger
(showShapes) && (crossUp)
Value
slowMa
Deps
crossUp:var, showShapes:input
MA Cross Down
line 362:9
Trigger
(showShapes) && (crossDown)
Value
slowMa
Deps
crossDown:var, showShapes:input
Price Cross Up
line 372:9
Trigger
(showShapes) && (priceCrossUp)
Value
regimeMa
Deps
priceCrossUp:var, showShapes:input
Price Cross Down
line 382:9
Trigger
(showShapes) && (priceCrossDown)
Value
regimeMa
Deps
priceCrossDown:var, showShapes:input
297_close_price.flowscript
source path: kscripts/perfected/297_close_price.flowscript · sha256:a5523ae13294b13171407fcc0f06e0eac86c20027b85f91d47e2a9145847d6cd
//@version=2
// ============================================================================
// Close Price Pro — Perfected Edition
// Author: L (@lam) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #price, #moving_average, #regime, #trend
//
// Production-quality close price analysis overlay. Implements multi-layer
// moving average ribbon, regime detection, dynamic volatility bands, and
// academic microstructure foundations for price-based signal generation.
//
// Research papers underpinning this design:
// 1. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread":
// Even the simplest close price exists within a bid-ask spread
// microstructure; the close is one realization from the bid-ask
// distribution. Expected returns are an increasing function of spread.
// 2. Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey":
// The close price emerges from the interaction of latent supply/demand,
// informed traders, and market maker inventory. The close reflects the
// equilibrium of all order flow up to that point.
// 3. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules":
// Moving average crossovers significantly outperformed buy-and-hold on
// 90 years of DJIA data. Buy signals followed by positive returns.
// 4. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
// Under plausible trend dynamics, the optimal trend-following strategy
// resembles the simple moving average crossover rule.
// 5. Manasa & Reddy (2025), "Trend Analysis by Weighted and EMA":
// Comparative study showing WMA responds faster but produces more
// whipsaws; EMA offers stability. A combined approach is recommended.
// ============================================================================
define(
title="Close Price Pro — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Price Smoothing ---
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=1,
label="Price Smoothing Length (1 = raw)",
constraints={min: 1, max: 50, step: 1},
group="Price Smoothing"
)
var smoothType = input(
name="smoothType",
type="select",
defaultValue="SMA",
label="Smoothing Type",
options=["SMA", "EMA", "WMA"],
group="Price Smoothing"
)
// --- Moving Averages ---
var fastMaLen = input(
name="fastMaLen",
type="number",
defaultValue=10,
label="Fast MA Length",
constraints={min: 2, max: 100, step: 1},
group="Moving Averages"
)
var slowMaLen = input(
name="slowMaLen",
type="number",
defaultValue=30,
label="Slow MA Length",
constraints={min: 5, max: 200, step: 1},
group="Moving Averages"
)
var maType = input(
name="maType",
type="select",
defaultValue="EMA",
label="MA Type",
options=["SMA", "EMA", "WMA", "VWMA"],
group="Moving Averages"
)
// --- Volatility Bands ---
var showBands = input(
name="showBands",
type="boolean",
defaultValue=true,
label="Show Volatility Bands",
group="Volatility Bands"
)
var bandPeriod = input(
name="bandPeriod",
type="number",
defaultValue=20,
label="Band Period (ATR)",
constraints={min: 5, max: 50, step: 1},
group="Volatility Bands"
)
var bandMult = input(
name="bandMult",
type="number",
defaultValue=2.0,
label="Band Multiplier",
constraints={min: 0.5, max: 5.0, step: 0.5},
group="Volatility Bands"
)
// --- Regime Detection ---
var enableRegime = input(
name="enableRegime",
type="boolean",
defaultValue=true,
label="Enable Regime Detection",
group="Regime Detection"
)
var regimeLen = input(
name="regimeLen",
type="number",
defaultValue=50,
label="Regime MA Length",
constraints={min: 10, max: 200, step: 1},
group="Regime Detection"
)
// --- Display ---
var showFastSlow = input(
name="showFastSlow",
type="boolean",
defaultValue=true,
label="Show Fast & Slow MAs",
group="Display"
)
var showRibbon = input(
name="showRibbon",
type="boolean",
defaultValue=true,
label="Show MA Ribbon Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Crossover Shapes",
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 bandColor = input(
name="bandColor",
type="color",
defaultValue="#2962ff",
label="Band Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. PRICE SMOOTHING
// -----------------------------------------------------------------------------
timeseries smoothPx = px
if (smoothLen > 1) {
if (smoothType == "SMA") {
smoothPx = sma(px, smoothLen)
} else if (smoothType == "EMA") {
smoothPx = ema(px, smoothLen)
} else if (smoothType == "WMA") {
smoothPx = wma(px, smoothLen)
}
}
// -----------------------------------------------------------------------------
// 4. MOVING AVERAGES
// -----------------------------------------------------------------------------
// Compute selected MA type for both fast and slow periods
timeseries fastMa = 0
timeseries slowMa = 0
timeseries regimeMa = 0
if (maType == "SMA") {
fastMa = sma(smoothPx, fastMaLen)
slowMa = sma(smoothPx, slowMaLen)
regimeMa = sma(smoothPx, regimeLen)
} else if (maType == "EMA") {
fastMa = ema(smoothPx, fastMaLen)
slowMa = ema(smoothPx, slowMaLen)
regimeMa = ema(smoothPx, regimeLen)
} else if (maType == "WMA") {
fastMa = wma(smoothPx, fastMaLen)
slowMa = wma(smoothPx, slowMaLen)
regimeMa = wma(smoothPx, regimeLen)
} else if (maType == "VWMA") {
fastMa = sma(smoothPx * bars.volume, fastMaLen) / math.max(sma(bars.volume, fastMaLen), 1.0)
slowMa = sma(smoothPx * bars.volume, slowMaLen) / math.max(sma(bars.volume, slowMaLen), 1.0)
regimeMa = sma(smoothPx * bars.volume, regimeLen) / math.max(sma(bars.volume, regimeLen), 1.0)
}
// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on price vs regime MA and fast vs slow MA
var regimeBull = enableRegime ? (smoothPx > regimeMa && fastMa > slowMa) : false
var regimeBear = enableRegime ? (smoothPx < regimeMa && fastMa < slowMa) : false
var regimeNeutral = enableRegime ? (!regimeBull && !regimeBear) : false
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// -----------------------------------------------------------------------------
// 6. VOLATILITY BANDS (ATR-based)
// -----------------------------------------------------------------------------
timeseries atr = tr(bars.high, bars.low, px)
timeseries atrSmoothed = rma(atr, bandPeriod)
timeseries upperBand = smoothPx + atrSmoothed * bandMult
timeseries lowerBand = smoothPx - atrSmoothed * bandMult
// -----------------------------------------------------------------------------
// 7. CROSSOVER ALERTS & STATIC TRACKING
// -----------------------------------------------------------------------------
// Fast/slow MA crossovers
var crossUp = fastMa > slowMa && fastMa[1] <= slowMa[1]
var crossDown = fastMa < slowMa && fastMa[1] >= slowMa[1]
// Price crossing regime MA
var priceCrossUp = smoothPx > regimeMa && smoothPx[1] <= regimeMa[1]
var priceCrossDown = smoothPx < regimeMa && smoothPx[1] >= regimeMa[1]
// Static tracking for consecutive regime bars
static bullBars = 0
static bearBars = 0
static lastRegime = 0
if (regimeBull) {
bullBars = bullBars + 1
bearBars = 0
lastRegime = 1
} else if (regimeBear) {
bearBars = bearBars + 1
bullBars = 0
lastRegime = -1
} else {
bullBars = 0
bearBars = 0
lastRegime = 0
}
// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------
// --- Smoothed Close Price (regime-colored) ---
plotLine(
value=smoothPx,
width=2,
colors=[regimeColor],
label=["Close Price"],
desc=["Smoothed close price (regime-colored) — the canonical reference series"]
)
// --- Volatility Bands ---
if (showBands) {
plotLine(
value=[upperBand, lowerBand],
width=1,
colors=[transparency(bandColor, 70), transparency(bandColor, 70)],
colorIndex=0,
fill=true,
label=["Upper Band", "Lower Band"],
desc=["ATR-based upper volatility band", "ATR-based lower volatility band"]
)
hline(value=upperBand, color=transparency(bandColor, 50), width=1)
hline(value=lowerBand, color=transparency(bandColor, 50), width=1)
}
// --- Fast & Slow MA Ribbon Fill ---
if (showRibbon && showFastSlow) {
var ribbonBull = fastMa > slowMa
plotLine(
value=[fastMa, slowMa],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=ribbonBull ? 0 : 1,
fill=true,
label=["Fast MA", "Slow MA"],
desc=["Fast MA ribbon edge", "Slow MA ribbon edge"]
)
}
// --- Individual Fast & Slow MA Lines ---
if (showFastSlow) {
plotLine(
value=fastMa,
width=2,
colors=[bullColor],
label=["Fast MA"],
desc=["Fast moving average (" + maType + " " + fastMaLen + ")"]
)
plotLine(
value=slowMa,
width=2,
colors=[bearColor],
label=["Slow MA"],
desc=["Slow moving average (" + maType + " " + slowMaLen + ")"]
)
}
// --- Regime MA ---
if (enableRegime) {
plotLine(
value=regimeMa,
width=1,
colors=[transparency(neutralColor, 50)],
label=["Regime MA"],
desc=["Regime detection moving average (" + regimeLen + ")"]
)
}
// --- Crossover Shapes ---
if (showShapes) {
if (crossUp) {
plotShape(
value=slowMa,
shape="triangleup",
colorIndex=bullColor,
width=2,
label=["MA Cross Up"],
desc=["Fast MA crossed above slow MA — bullish alignment"]
)
}
if (crossDown) {
plotShape(
value=slowMa,
shape="triangledown",
colorIndex=bearColor,
width=2,
label=["MA Cross Down"],
desc=["Fast MA crossed below slow MA — bearish alignment"]
)
}
if (priceCrossUp) {
plotShape(
value=regimeMa,
shape="circle",
colorIndex=bullColor,
width=2,
label=["Price Cross Up"],
desc=["Price crossed above regime MA"]
)
}
if (priceCrossDown) {
plotShape(
value=regimeMa,
shape="circle",
colorIndex=bearColor,
width=2,
label=["Price Cross Down"],
desc=["Price crossed below regime MA"]
)
}
}
// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["Close Price Pro", regimeText],
["Close", smoothPx[0]],
["Fast MA", fastMa[0]],
["Slow MA", slowMa[0]],
["Regime MA", regimeMa[0]],
["Upper Band", upperBand[0]],
["Lower Band", lowerBand[0]],
["Bull Bars", bullBars],
["Bear Bars", bearBars]
],
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
)
}