Perfected FlowScript
Market Cipher B - ULTIMATE -
Market Cipher B — Perfected Edition is indexed as 032_market_cipher_b_ultimate.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
offchart
Axis
true
Size
18.1 KB
Lines
611
Native Signal Candidates
7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
WT Cross Up
line 498:9
Trigger
(showAlerts) && (wtCrossUp)
Value
wt1
Deps
showAlerts:input, wtCrossUp:var
WT Cross Down
line 508:9
Trigger
(showAlerts) && (wtCrossDown)
Value
wt1
Deps
showAlerts:input, wtCrossDown:var
Bull Signal
line 522:9
Trigger
(showAlerts) && (compositeCrossUp)
Value
composite
Deps
compositeCrossUp:var, showAlerts:input
Bear Signal
line 532:9
Trigger
(showAlerts) && (compositeCrossDown)
Value
composite
Deps
compositeCrossDown:var, showAlerts:input
Extreme OB
line 546:9
Trigger
(showAlerts) && (extremeOb)
Value
composite
Deps
extremeOb:var, showAlerts:input
Extreme OS
line 556:9
Trigger
(showAlerts) && (extremeOs)
Value
composite
Deps
extremeOs:var, showAlerts:input
Vol Weak
line 569:5
Trigger
(showAlerts && volConfirmAlert)
Value
composite
Deps
showAlerts:input, volConfirmAlert:var
032_market_cipher_b_ultimate.flowscript
source path: kscripts/perfected/032_market_cipher_b_ultimate.flowscript · sha256:58f33f9980cf55128e6ce51ab48d69d88ca3767c1331b8af0aef0fc06914b859
//@version=2
// ============================================================================
// Market Cipher B — Perfected Edition
// Author: Mars2035_ (@Mars2035_) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #momentum, #trend, #volume, #composite
//
// Production-grade multi-oscillator composite combining WaveTrend momentum
// analysis, enhanced RSI with dynamic color alerts, and Money Flow Index for
// capital flow measurement. Features composite scoring, dynamic regime-based
// color coding, volume-weighted confirmation, OB/OS zone fills, and
// comprehensive signal shape alerts.
//
// Research papers underpinning this design:
// 1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
// RSI reference. RSI = 100 − [100 / (1 + RS)] where RS = avgGain / avgLoss.
// The enhanced RSI component extends Wilder's original 0–100 framework.
// 2. Quong & Soudack (1989), "Money Flow Index" (Stocks & Commodities, Mar 1989):
// introduced MFI as a volume-weighted RSI. Typical Price = (H+L+C)/3;
// Raw Money Flow = TP × Volume; MFI = 100 − [100 / (1 + MFR)].
// 3. Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability":
// found no single indicator fully reliable; recommends combining multiple
// indicators. The script's multi-oscillator composite directly implements
// this recommendation.
// 4. Hutabarat, Sadalia & Irawati (2025), "Technical Analysis of MACD, SO,
// RSI, and MFI" (IJCSRR): multi-indicator accuracy comparison on IDX30.
// Supports the composite approach where confluence of multiple oscillators
// improves signal reliability.
// 5. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers"
// (J. Finance): established momentum as a premier cross-sectional anomaly.
// Validates the WaveTrend and RSI momentum components as measures of price
// persistence and trend strength.
// ============================================================================
define(
title="Market Cipher B — Perfected Edition",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- WaveTrend ---
var wtChannelLen = input(
name="wtChannelLen",
type="number",
defaultValue=10,
label="WT Channel Length",
constraints={min: 2, max: 50, step: 1},
group="WaveTrend"
)
var wtAvgLen = input(
name="wtAvgLen",
type="number",
defaultValue=21,
label="WT Average Length",
constraints={min: 2, max: 50, step: 1},
group="WaveTrend"
)
var wtSignalLen = input(
name="wtSignalLen",
type="number",
defaultValue=4,
label="WT Signal Length",
constraints={min: 2, max: 20, step: 1},
group="WaveTrend"
)
// --- Enhanced RSI ---
var rsiLen = input(
name="rsiLen",
type="number",
defaultValue=14,
label="RSI Length",
constraints={min: 2, max: 50, step: 1},
group="Enhanced RSI"
)
var rsiSmooth = input(
name="rsiSmooth",
type="number",
defaultValue=3,
label="RSI Smoothing",
constraints={min: 1, max: 20, step: 1},
group="Enhanced RSI"
)
var useWilderRsi = input(
name="useWilderRsi",
type="boolean",
defaultValue=true,
label="Use Wilder Smoothing",
group="Enhanced RSI"
)
// --- Money Flow Index ---
var mfiLen = input(
name="mfiLen",
type="number",
defaultValue=14,
label="MFI Length",
constraints={min: 2, max: 50, step: 1},
group="Money Flow Index"
)
// --- Thresholds ---
var obLevel = input(
name="obLevel",
type="number",
defaultValue=70,
label="OB Level",
constraints={min: 50, max: 95, step: 1},
group="Thresholds"
)
var osLevel = input(
name="osLevel",
type="number",
defaultValue=30,
label="OS Level",
constraints={min: 5, max: 50, step: 1},
group="Thresholds"
)
var wtOb = input(
name="wtOb",
type="number",
defaultValue=60,
label="WaveTrend OB Level",
constraints={min: 0, max: 100, step: 1},
group="Thresholds"
)
var wtOs = input(
name="wtOs",
type="number",
defaultValue=-60,
label="WaveTrend OS Level",
constraints={min: -100, max: 0, step: 1},
group="Thresholds"
)
// --- Composite ---
var wtWeight = input(
name="wtWeight",
type="number",
defaultValue=0.30,
label="WaveTrend Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Composite"
)
var rsiWeight = input(
name="rsiWeight",
type="number",
defaultValue=0.35,
label="RSI Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Composite"
)
var mfiWeight = input(
name="mfiWeight",
type="number",
defaultValue=0.35,
label="MFI Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Composite"
)
var compositeThreshold = input(
name="compositeThreshold",
type="number",
defaultValue=55,
label="Composite Bull Threshold",
constraints={min: 50, max: 80, step: 1},
group="Composite"
)
var compositeBearThreshold = input(
name="compositeBearThreshold",
type="number",
defaultValue=45,
label="Composite Bear Threshold",
constraints={min: 20, max: 50, step: 1},
group="Composite"
)
// --- Display ---
var showWT = input(
name="showWT",
type="boolean",
defaultValue=true,
label="Show WaveTrend",
group="Display"
)
var showRSI = input(
name="showRSI",
type="boolean",
defaultValue=true,
label="Show Enhanced RSI",
group="Display"
)
var showMFI = input(
name="showMFI",
type="boolean",
defaultValue=true,
label="Show MFI",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Score",
group="Display"
)
var showZones = input(
name="showZones",
type="boolean",
defaultValue=true,
label="Show OB/OS Zones",
group="Display"
)
var showAlerts = input(
name="showAlerts",
type="boolean",
defaultValue=true,
label="Show Alert 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 wtColor = input(
name="wtColor",
type="color",
defaultValue="#2962ff",
label="WaveTrend Color",
group="Colors"
)
var rsiColor = input(
name="rsiColor",
type="color",
defaultValue="#ff6d00",
label="RSI Color",
group="Colors"
)
var mfiColor = input(
name="mfiColor",
type="color",
defaultValue="#26a69a",
label="MFI Color",
group="Colors"
)
var compositeColor = input(
name="compositeColor",
type="color",
defaultValue="#ffd700",
label="Composite Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume
if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. WAVETREND COMPUTATION
// -----------------------------------------------------------------------------
// WaveTrend: ESA = EMA of Typical Price over channel length; D = EMA of
// |Typical - ESA|; CI = (Typical - ESA) / (0.015 * D); WT1 = EMA(CI, avg).
timeseries typ = (hi + lo + px) / 3
timeseries esa = ema(typ, wtChannelLen)
timeseries d = ema(math.abs(typ - esa), wtChannelLen)
timeseries ci = d > 0 ? (typ - esa) / (0.015 * d) : 0
timeseries wt1 = ema(ci, wtAvgLen)
timeseries wt2 = sma(wt1, wtSignalLen)
// -----------------------------------------------------------------------------
// 4. ENHANCED RSI
// -----------------------------------------------------------------------------
// Canonical Wilder RSI with optional smoothing
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = useWilderRsi ? ema(gain, rsiLen) : sma(gain, rsiLen)
timeseries avgLoss = useWilderRsi ? ema(loss, rsiLen) : sma(loss, rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
timeseries rsiSeries = rsiSmooth > 1 ? ema(rsiRaw, rsiSmooth) : rsiRaw
// -----------------------------------------------------------------------------
// 5. MONEY FLOW INDEX
// -----------------------------------------------------------------------------
// Per Quong & Soudack (1989): volume-weighted RSI using typical price.
timeseries rawFlow = typ * vol
timeseries posFlow = (typ > typ[1]) ? rawFlow : 0
timeseries negFlow = (typ < typ[1]) ? rawFlow : 0
timeseries posSum = sum(posFlow, mfiLen)
timeseries negSum = sum(negFlow, mfiLen)
// Edge-case handling: when negSum = 0 and posSum > 0, MFI = 100
timeseries mfiRatio = negSum > 0 ? posSum / negSum : (posSum > 0 ? 999999 : 1)
timeseries mfiSeries = 100 - (100 / (1 + mfiRatio))
// -----------------------------------------------------------------------------
// 6. COMPOSITE SCORING
// -----------------------------------------------------------------------------
// Normalize WaveTrend (roughly -100 to +100) to 0-100 scale
timeseries wtClamped = math.max(-100, math.min(100, wt1))
timeseries wtNorm = (wtClamped + 100) / 2
// Weighted composite score (0-100)
timeseries composite = wtNorm * wtWeight + rsiSeries * rsiWeight + mfiSeries * mfiWeight
// Volume-weighted confirmation: MFI must agree with composite direction
var compositeBull = composite > compositeThreshold
var compositeBear = composite < compositeBearThreshold
var compositeNeutral = !compositeBull && !compositeBear
// Volume confirmation: MFI > 50 for bullish, MFI < 50 for bearish
var volumeConfirmsBull = mfiSeries > 50
var volumeConfirmsBear = mfiSeries < 50
var confirmedBull = compositeBull && volumeConfirmsBull
var confirmedBear = compositeBear && volumeConfirmsBear
var regimeColor = compositeBull ? bullColor : (compositeBear ? bearColor : neutralColor)
// Count of bullish indicators (0-3)
var bullCount = (wt1 > wt2 ? 1 : 0) + (rsiSeries > 50 ? 1 : 0) + (mfiSeries > 50 ? 1 : 0)
// -----------------------------------------------------------------------------
// 7. STATIC SIGNAL STATE
// -----------------------------------------------------------------------------
static barCount = 0
static lastSignal = 0 // 1 = bull, -1 = bear, 0 = none
static signalBar = 0
static barsSinceSignal = 0
static extremeCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
// Track signal changes
if (confirmedBull && lastSignal != 1) {
lastSignal = 1
signalBar = barCount
barsSinceSignal = 0
} else if (confirmedBear && lastSignal != -1) {
lastSignal = -1
signalBar = barCount
barsSinceSignal = 0
} else {
barsSinceSignal = barsSinceSignal + 1
}
// Track extreme readings (all three in OB or OS)
if (wt1 > wtOb && rsiSeries > obLevel && mfiSeries > obLevel) {
extremeCount = extremeCount + 1
} else if (wt1 < wtOs && rsiSeries < osLevel && mfiSeries < osLevel) {
extremeCount = extremeCount + 1
}
}
// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// WaveTrend crossover
var wtCrossUp = wt1 > wt2 && wt1[1] <= wt2[1]
var wtCrossDown = wt1 < wt2 && wt1[1] >= wt2[1]
// Composite signal
var compositeCrossUp = composite > compositeThreshold && composite[1] <= compositeThreshold
var compositeCrossDown = composite < compositeBearThreshold && composite[1] >= compositeBearThreshold
// OB / OS penetrations
var obPenetrate = composite > obLevel && composite[1] <= obLevel
var osPenetrate = composite < osLevel && composite[1] >= osLevel
// Extreme confluence: all three indicators in OB or OS
var extremeOb = wt1 > wtOb && rsiSeries > obLevel && mfiSeries > obLevel
var extremeOs = wt1 < wtOs && rsiSeries < osLevel && mfiSeries < osLevel
// Volume confirmation alert
var volConfirmAlert = (compositeBull && !volumeConfirmsBull) || (compositeBear && !volumeConfirmsBear)
// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------
// --- WaveTrend Lines ---
if (showWT) {
plotLine(
value=wt1,
width=2,
colors=[wtColor],
label=["WT1"],
desc=["WaveTrend oscillator line 1 (" + wtChannelLen + "/" + wtAvgLen + ")"]
)
plotLine(
value=wt2,
width=1,
colors=["#ffffff80"],
label=["WT2"],
desc=["WaveTrend signal line (SMA " + wtSignalLen + ")"]
)
}
// --- Enhanced RSI ---
if (showRSI) {
plotLine(
value=rsiSeries,
width=2,
colors=[rsiColor],
label=["RSI"],
desc=["Enhanced smoothed RSI (" + rsiLen + ")"]
)
}
// --- MFI ---
if (showMFI) {
plotLine(
value=mfiSeries,
width=1,
colors=[mfiColor],
label=["MFI"],
desc=["Money Flow Index (" + mfiLen + ") — volume-weighted RSI"]
)
}
// --- Composite Score ---
if (showComposite) {
plotLine(
value=composite,
width=2,
colors=[regimeColor],
label=["Composite"],
desc=["Weighted composite score (WT+RSI+MFI)"]
)
plotLine(
value=composite,
width=1,
colors=[compositeColor],
label=["Composite Base"],
desc=["Composite base line"]
)
}
// --- OB / OS Zones ---
if (showZones) {
hline(value=obLevel, color=transparency(bearColor, 60), width=1)
hline(value=osLevel, color=transparency(bullColor, 60), width=1)
hline(value=wtOb, color=transparency(bearColor, 40), width=1)
hline(value=wtOs, color=transparency(bullColor, 40), width=1)
hline(value=50, color="#ffffff20", width=1)
hline(value=0, color="#ffffff20", width=1)
}
// --- Composite Fill (regime-based) ---
if (showComposite) {
var fillBull = composite > 50
plotLine(
value=[composite, 50],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Composite", "Midline"],
desc=["Composite score fill", "50 midline"]
)
}
// --- WaveTrend Crossover Shapes ---
if (showAlerts) {
if (wtCrossUp) {
plotShape(
value=wt1,
shape="triangleup",
colorIndex=wtColor,
width=2,
label=["WT Cross Up"],
desc=["WaveTrend crossed above signal line"]
)
}
if (wtCrossDown) {
plotShape(
value=wt1,
shape="triangledown",
colorIndex=wtColor,
width=2,
label=["WT Cross Down"],
desc=["WaveTrend crossed below signal line"]
)
}
}
// --- Composite Signal Shapes ---
if (showAlerts) {
if (compositeCrossUp) {
plotShape(
value=composite,
shape="triangleup",
colorIndex=confirmedBull ? bullColor : neutralColor,
width=3,
label=["Bull Signal"],
desc=["Composite crossed above bull threshold" + (confirmedBull ? " (volume confirmed)" : " (unconfirmed)")]
)
}
if (compositeCrossDown) {
plotShape(
value=composite,
shape="triangledown",
colorIndex=confirmedBear ? bearColor : neutralColor,
width=3,
label=["Bear Signal"],
desc=["Composite crossed below bear threshold" + (confirmedBear ? " (volume confirmed)" : " (unconfirmed)")]
)
}
}
// --- Extreme Confluence Shapes ---
if (showAlerts) {
if (extremeOb) {
plotShape(
value=composite,
shape="xcross",
colorIndex=transparency(bearColor, 80),
width=2,
label=["Extreme OB"],
desc=["All three oscillators in overbought zone"]
)
}
if (extremeOs) {
plotShape(
value=composite,
shape="xcross",
colorIndex=transparency(bullColor, 80),
width=2,
label=["Extreme OS"],
desc=["All three oscillators in oversold zone"]
)
}
}
// --- Volume Confirmation Warning ---
if (showAlerts && volConfirmAlert) {
plotShape(
value=composite,
shape="circle",
colorIndex=transparency(compositeColor, 60),
width=1,
label=["Vol Weak"],
desc=["Composite signal lacks volume confirmation"]
)
}
// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = compositeBull ? "BULLISH" : (compositeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeColor
var confirmText = confirmedBull ? "CONFIRMED" : (confirmedBear ? "CONFIRMED" : (compositeBull || compositeBear ? "UNCONFIRMED" : "—"))
plotTable(
data=[
["Market Cipher B — Perfected", regimeText],
["WaveTrend", wt1[0]],
["RSI", rsiSeries[0]],
["MFI", mfiSeries[0]],
["Composite", composite[0]],
["Bull Count", bullCount],
["Volume", confirmText],
["Extreme Events", extremeCount]
],
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
)
}