本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, obtain one at https://mozilla.org/MPL/2.0/.
// © WizTrader
//@version=6
indicator("WizTrader Trend Flow MTF", shorttitle="Wiz Flow", overlay=true, scale=scale.none,
explicit_plot_zorder=false, dynamic_requests=true)
// WIZTRADER TREND FLOW MTF · v1.0
// Fast and Slow Flow: a classic two-stage EMA of the close plus a bounded,
// RSI-directed candle-body correction, itself smoothed twice at half length.
// Direction is the sign of the change versus the previous candle; zero is neutral.
// Both chart curves are live previews. Turns/alerts require chart close.
// MTF tiles use the fast filter on completed source candles; slow is chart-only.
// Intrabars use security_lower_tf arrays. Auto selects chart-relative horizons.
// Context phases distinguish a counter-move from its subsequently observed recovery.
string groupModel = "Trend Flow"
int filterLength = input.int(20, "Fast Length", minval=5, maxval=100, group=groupModel,
tooltip="Base length of the two fixed EMA stages in Fast Flow. Price source is always Close. RSI Body Response is always active and adds a separate price correction smoothed twice at half this length, rounded to the nearest integer with a minimum of 2. Defaults: base 20, correction 10. Each Fast MTF context runs the same calculation independently. Direction needs 3 x base length + 1 valid candles. Direction always compares with the previous candle; there is no lookback setting.")
int slowLength = input.int(70, "Slow Length", minval=5, maxval=300, group=groupModel,
tooltip="Slow Flow always uses Close and the same active RSI Body Response calculation as Fast at its own lengths. Defaults: base 70, correction 35. It is chart-only. Direction needs 3 x base length + 1 valid candles: 211 at defaults. Direction always compares with the previous candle. Its slope and position relative to Fast also affect context phases and recovery alerts, even when hidden.")
int slopeBars = 1
float neutralZone = 0.0
string groupMtf = "Multi-Timeframe Dashboard"
string tfPreset = input.string("Auto", "Timeframe Mode", options=["Auto", "Custom"], group=groupMtf,
tooltip="Auto centers five horizons on this chart: normally two lower, the chart, and two higher intervals. Targets are approximately 1/4, 1/2, 1, 2 and 4 times the chart interval, rounded outward to a supported interval ladder. Example on 1H: 15m / 30m / 1H / 2H / 4H. At the smallest/largest supported intervals the available range takes priority. Custom uses the five fields below. These are context choices, not optimized trading lengths.")
string custom1 = input.timeframe("15", "Custom Timeframe 1", group=groupMtf)
string custom2 = input.timeframe("30", "Custom Timeframe 2", group=groupMtf)
string custom3 = input.timeframe("60", "Custom Timeframe 3", group=groupMtf)
string custom4 = input.timeframe("120", "Custom Timeframe 4", group=groupMtf)
string custom5 = input.timeframe("240", "Custom Timeframe 5", group=groupMtf)
bool showContext = input.bool(true, "Show Context Phase", group=groupMtf,
tooltip="On chart close, distinguish higher-timeframe context, a counter-move, and an observed recovery. Requires two increasing lower intervals, this exact chart interval in slot 3, and two increasing higher intervals. The two higher Fast states must agree. Chart Slow slope and Fast/Slow order must support that direction. A counter-move is an opposing lower/chart Fast state or a close on the opposing side of Fast. Recovery requires a counter-move observed at an earlier chart close, followed by all five Fast states and price returning to context direction. Missing data, lost chart support or changed higher context cancels memory. Recovery is an observation, not a trade or prediction. This switch hides the phase row only; detection and alerts stay active.")
int alignmentRequired = input.int(4, "MTF Alert: Minimum Agreement", minval=3, maxval=5, group=groupMtf,
tooltip="An alignment alert requires at least this many of the five tiles to point in one direction, with data available for all five. Alerts occur only on chart candle close, when that threshold becomes newly satisfied. Dashboard majority and curve direction are separate observations.")
string groupDisplay = "Display"
bool showSlowFlow = input.bool(true, "Show Slow Flow", group=groupDisplay,
tooltip="Show Slow Flow on the chart with its own compact glow. Hiding it also hides the gradient between the curves. Fast Flow and the MTF dashboard remain independent of this display choice.")
bool showGradientFill = input.bool(true, "Gradient Fill", group=groupDisplay,
tooltip="Fill between Fast Flow and Slow Flow. The Up color means Fast is above Slow; the Down color means Fast is below Slow. Color fades from Fast toward Slow and becomes lighter on the open candle. This describes relative line position, not slope direction or MTF agreement. The fill appears only after both chart filters are ready. It is hidden when Show Slow Flow is off. It is not a stop, forecast or support/resistance zone.")
string fillIntensity = input.string("Medium", "Fill Intensity", options=["Soft", "Medium", "Strong"], group=groupDisplay,
tooltip="Opacity near Fast Flow. Every setting fades toward full transparency at Slow Flow. Glow is controlled separately. The fill is drawn behind the curve strokes so it does not dim their central lines.")
string glowMode = input.string("Strong", "Glow", options=["Off", "Soft", "Strong"], group=groupDisplay,
tooltip="Both curves use centered pixel strokes: Strong has a 12-pixel outer halo, 6-pixel light rim and 2-pixel core; Soft uses 9/4/2. Full selected direction colors are retained. Glow brightness follows a four-candle EMA of whether the non-neutral direction repeated, eased continuously. Slow halos are slightly lighter than Fast halos. This is a display rhythm, not a strength or probability score. Open-candle cores and glows are faded previews. Off removes halos while keeping the curves, enabled inter-line gradient and markers.")
bool showTurns = input.bool(true, "Confirmed Turn Dots", group=groupDisplay,
tooltip="Small dots on Fast Flow mark a confirmed change from the last non-neutral direction to its opposite. Neutral candles do not erase that remembered direction. The first direction after warm-up or a data reset receives no turn dot. Visibility does not affect alerts.")
bool showPriceBreaks = input.bool(false, "Price Break Markers", group=groupDisplay,
tooltip="Optional small triangles: Up-colored below a candle when its close crosses above Fast Flow; Down-colored above a candle when its close crosses below Fast Flow. Both the current and previous filter states must be ready. Only completed candles qualify; wick-only crossings and a close exactly on the curve do not. Each close is compared with its own candle's moving curve value. These events are independent of trend-turn dots and MTF alignment. Hiding markers does not disable their alerts.")
string barColorMode = input.string("Off", "Bar Colors", options=["Off", "Gradient", "Solid"], group=groupDisplay,
tooltip="Optional chart candle coloring. Off preserves the chart colors. Solid follows Fast Flow direction using the selected Up, Down and Neutral colors. Gradient blends from Neutral toward the Fast direction color: saturation increases when chart Slow direction and Fast/Slow order agree with Fast, moderated by the same smoothed Fast direction continuity used for glow. Missing Slow data contributes no agreement. This is chart-only styling, independent of candle body direction and MTF votes. Exact neutral Fast uses Neutral; unavailable Fast preserves chart colors. The open candle uses 18% transparency and may change before close. Slow visibility and Glow do not affect bar colors. No signals or alerts are changed.")
bool showDashboard = input.bool(true, "Show MTF Dashboard", group=groupDisplay)
string dashboardPosition = input.string("Bottom Right", "Dashboard Position", options=["Bottom Right", "Bottom Left", "Top Right", "Top Left"], group=groupDisplay)
string dashboardSize = input.string("Medium", "Dashboard Size", options=["Small", "Medium", "Large"], group=groupDisplay)
string groupColors = "Colors"
color upColor = input.color(color.rgb(85, 134, 219), "Up", group=groupColors)
color downColor = input.color(color.rgb(172, 68, 203), "Down", group=groupColors)
color neutralColor = input.color(color.rgb(100, 100, 120), "Neutral / Unavailable", group=groupColors)
f_canonical(simple string tf) =>
string resolved = tf == "" ? timeframe.period : tf
resolved == "D" ? "1D" : resolved == "W" ? "1W" : resolved == "M" ? "1M" : resolved
f_tfText(string tf) =>
float minutes = str.tonumber(tf)
na(minutes) ? tf : minutes >= 60.0 and minutes % 60.0 == 0.0 ? str.tostring(minutes / 60.0, "0") + "H" : str.tostring(minutes, "0") + "m"
// Outward interval rounding uses a fixed duration ladder; the chart slot stays exact.
f_lowerTf(simple float target) =>
string result = "1S"
if target >= timeframe.in_seconds("12M")
result := "12M"
else if target >= timeframe.in_seconds("9M")
result := "9M"
else if target >= timeframe.in_seconds("6M")
result := "6M"
else if target >= timeframe.in_seconds("3M")
result := "3M"
else if target >= timeframe.in_seconds("2M")
result := "2M"
else if target >= timeframe.in_seconds("1M")
result := "1M"
else if target >= 1209600.0
result := "2W"
else if target >= 604800.0
result := "1W"
else if target >= 345600.0
result := "4D"
else if target >= 259200.0
result := "3D"
else if target >= 172800.0
result := "2D"
else if target >= 86400.0
result := "1D"
else if target >= 43200.0
result := "720"
else if target >= 28800.0
result := "480"
else if target >= 21600.0
result := "360"
else if target >= 14400.0
result := "240"
else if target >= 10800.0
result := "180"
else if target >= 7200.0
result := "120"
else if target >= 5400.0
result := "90"
else if target >= 3600.0
result := "60"
else if target >= 2700.0
result := "45"
else if target >= 1800.0
result := "30"
else if target >= 1200.0
result := "20"
else if target >= 900.0
result := "15"
else if target >= 600.0
result := "10"
else if target >= 300.0
result := "5"
else if target >= 180.0
result := "3"
else if target >= 120.0
result := "2"
else if target >= 60.0
result := "1"
else if target >= 45.0
result := "45S"
else if target >= 30.0
result := "30S"
else if target >= 15.0
result := "15S"
else if target >= 10.0
result := "10S"
else if target >= 5.0
result := "5S"
else if target >= 1.0
result := "1S"
result
f_upperTf(simple float target) =>
string result = "12M"
if target <= 1.0
result := "1S"
else if target <= 5.0
result := "5S"
else if target <= 10.0
result := "10S"
else if target <= 15.0
result := "15S"
else if target <= 30.0
result := "30S"
else if target <= 45.0
result := "45S"
else if target <= 60.0
result := "1"
else if target <= 120.0
result := "2"
else if target <= 180.0
result := "3"
else if target <= 300.0
result := "5"
else if target <= 600.0
result := "10"
else if target <= 900.0
result := "15"
else if target <= 1200.0
result := "20"
else if target <= 1800.0
result := "30"
else if target <= 2700.0
result := "45"
else if target <= 3600.0
result := "60"
else if target <= 5400.0
result := "90"
else if target <= 7200.0
result := "120"
else if target <= 10800.0
result := "180"
else if target <= 14400.0
result := "240"
else if target <= 21600.0
result := "360"
else if target <= 28800.0
result := "480"
else if target <= 43200.0
result := "720"
else if target <= 86400.0
result := "1D"
else if target <= 172800.0
result := "2D"
else if target <= 259200.0
result := "3D"
else if target <= 345600.0
result := "4D"
else if target <= 604800.0
result := "1W"
else if target <= 1209600.0
result := "2W"
else if target <= timeframe.in_seconds("1M")
result := "1M"
else if target <= timeframe.in_seconds("2M")
result := "2M"
else if target <= timeframe.in_seconds("3M")
result := "3M"
else if target <= timeframe.in_seconds("6M")
result := "6M"
else if target <= timeframe.in_seconds("9M")
result := "9M"
else if target <= timeframe.in_seconds("12M")
result := "12M"
result
if not chart.is_standard or str.contains(timeframe.period, "T")
runtime.error("WizTrader Trend Flow MTF needs a standard, time-based price chart. Use Candles or Bars.")
// Each call has its own two-stage state, including each requested context.
// Missing/invalid OHLC explicitly resets both stages and the warm-up counter.
f_model() =>
bool validPrice = not na(open) and not na(high) and not na(low) and not na(close) and
high >= math.max(open, close) and low <= math.min(open, close)
float price = close
float alpha = 2.0 / (filterLength + 1.0)
int correctionLength = math.max(2, int(math.round(filterLength / 2.0)))
float correctionAlpha = 2.0 / (correctionLength + 1.0)
float atr = ta.atr(14)
float rsi = ta.rsi(validPrice ? price : na, 14)
var float stage1 = na
var float stage2 = na
var float bodyResponse1 = 0.0
var float bodyResponse2 = 0.0
var int validCount = 0
if validPrice
stage1 := na(stage1) ? price : stage1 + alpha * (price - stage1)
stage2 := na(stage2) ? stage1 : stage2 + alpha * (stage1 - stage2)
float targetCorrection = 0.0
if not na(rsi) and not na(atr)
float centeredRsi = (rsi - 50.0) / 50.0
float pressure = centeredRsi / (0.25 + math.abs(centeredRsi))
float bodyMid = (open + close) * 0.5
float bodyHalf = math.abs(close - open) * 0.5
float bodyAnchor = bodyMid - pressure * bodyHalf
float gap = bodyAnchor - stage2
float scale = math.max(atr, syminfo.mintick)
float normalizedGap = gap / scale
float gapDirection = normalizedGap / math.sqrt(normalizedGap * normalizedGap + 0.01)
float agreement = math.max(0.0, pressure * gapDirection)
float rawCorrection = 0.8 * agreement * gap
float cap = math.max(2.0 * atr, syminfo.mintick)
float ratio = rawCorrection / cap
targetCorrection := rawCorrection / math.sqrt(1.0 + ratio * ratio)
bodyResponse1 := bodyResponse1 + correctionAlpha * (targetCorrection - bodyResponse1)
bodyResponse2 := bodyResponse2 + correctionAlpha * (bodyResponse1 - bodyResponse2)
validCount += 1
else
stage1 := na
stage2 := na
bodyResponse1 := 0.0
bodyResponse2 := 0.0
validCount := 0
float curve = stage2 + bodyResponse2
bool ready = validCount >= 3 * filterLength + slopeBars and not na(curve[slopeBars]) and not na(atr)
float normalizedSlope = ready ? (curve - curve[slopeBars]) / math.max(atr, syminfo.mintick) : na
int direction = na
if ready
direction := normalizedSlope > neutralZone ? 1 : normalizedSlope < -neutralZone ? -1 : 0
[curve, direction, normalizedSlope]
// Independent chart-only slow filter; never requested by MTF sampling.
f_slowModel() =>
bool validPrice = not na(open) and not na(high) and not na(low) and not na(close) and
high >= math.max(open, close) and low <= math.min(open, close)
float price = close
float alpha = 2.0 / (slowLength + 1.0)
int correctionLength = math.max(2, int(math.round(slowLength / 2.0)))
float correctionAlpha = 2.0 / (correctionLength + 1.0)
float atr = ta.atr(14)
float rsi = ta.rsi(validPrice ? price : na, 14)
var float stage1 = na
var float stage2 = na
var float bodyResponse1 = 0.0
var float bodyResponse2 = 0.0
var int validCount = 0
if validPrice
stage1 := na(stage1) ? price : stage1 + alpha * (price - stage1)
stage2 := na(stage2) ? stage1 : stage2 + alpha * (stage1 - stage2)
float targetCorrection = 0.0
if not na(rsi) and not na(atr)
float centeredRsi = (rsi - 50.0) / 50.0
float pressure = centeredRsi / (0.25 + math.abs(centeredRsi))
float bodyMid = (open + close) * 0.5
float bodyHalf = math.abs(close - open) * 0.5
float bodyAnchor = bodyMid - pressure * bodyHalf
float gap = bodyAnchor - stage2
float scale = math.max(atr, syminfo.mintick)
float normalizedGap = gap / scale
float gapDirection = normalizedGap / math.sqrt(normalizedGap * normalizedGap + 0.01)
float agreement = math.max(0.0, pressure * gapDirection)
float rawCorrection = 0.8 * agreement * gap
float cap = math.max(2.0 * atr, syminfo.mintick)
float ratio = rawCorrection / cap
targetCorrection := rawCorrection / math.sqrt(1.0 + ratio * ratio)
bodyResponse1 := bodyResponse1 + correctionAlpha * (targetCorrection - bodyResponse1)
bodyResponse2 := bodyResponse2 + correctionAlpha * (bodyResponse1 - bodyResponse2)
validCount += 1
else
stage1 := na
stage2 := na
bodyResponse1 := 0.0
bodyResponse2 := 0.0
validCount := 0
float curve = stage2 + bodyResponse2
bool ready = validCount >= 3 * slowLength + slopeBars and not na(curve[slopeBars]) and not na(atr)
float normalizedSlope = ready ? (curve - curve[slopeBars]) / math.max(atr, syminfo.mintick) : na
int direction = na
if ready
direction := normalizedSlope > neutralZone ? 1 : normalizedSlope < -neutralZone ? -1 : 0
[curve, direction, normalizedSlope]
f_state() =>
[value, direction, slope] = f_model()
direction
f_closedPayload() =>
int direction = f_state()
[direction[1], time_close[1]]
[flow, chartState, chartSlope] = f_model()
[slowFlow, slowState, slowSlope] = f_slowModel()
int chartClosedState = barstate.isconfirmed ? chartState : chartState[1]
int chartClosedTime = barstate.isconfirmed ? time_close : time_close[1]
float chartSeconds = timeframe.in_seconds()
bool tinyChart = chartSeconds < 10.0
bool nearCeiling = chartSeconds > timeframe.in_seconds("9M") / 2.0
bool atCeiling = chartSeconds >= timeframe.in_seconds("10M")
string rawAuto1 = tinyChart ? "1S" : atCeiling ? "1M" : f_lowerTf(chartSeconds / 4.0)
string auto2 = tinyChart ? "5S" : atCeiling ? "3M" : f_lowerTf(chartSeconds / 2.0)
// If outward rounding merged the lower targets, move the first down one rung.
string auto1 = not tinyChart and timeframe.in_seconds(rawAuto1) >= timeframe.in_seconds(auto2) ? f_lowerTf(timeframe.in_seconds(auto2) - 1.0) : rawAuto1
string auto3 = tinyChart ? "10S" : atCeiling ? "6M" : f_canonical(timeframe.period)
string auto4 = tinyChart ? "15S" : atCeiling ? (chartSeconds >= timeframe.in_seconds("12M") ? "9M" : f_canonical(timeframe.period)) :
nearCeiling ? str.tostring(int(math.round(chartSeconds / timeframe.in_seconds("1M"))) + 1) + "M" : f_upperTf(chartSeconds * 2.0)
string auto5 = tinyChart ? "30S" : atCeiling ? (chartSeconds >= timeframe.in_seconds("12M") ? f_canonical(timeframe.period) : "12M") : f_upperTf(chartSeconds * 4.0)
string tf1 = f_canonical(tfPreset == "Auto" ? auto1 : custom1)
string tf2 = f_canonical(tfPreset == "Auto" ? auto2 : custom2)
string tf3 = f_canonical(tfPreset == "Auto" ? auto3 : custom3)
string tf4 = f_canonical(tfPreset == "Auto" ? auto4 : custom4)
string tf5 = f_canonical(tfPreset == "Auto" ? auto5 : custom5)
if str.contains(tf1, "T") or str.contains(tf2, "T") or str.contains(tf3, "T") or str.contains(tf4, "T") or str.contains(tf5, "T")
runtime.error("Select time-based dashboard timeframes; tick intervals are not supported.")
if barstate.isfirst
array<int> durations = array.from(timeframe.in_seconds(tf1), timeframe.in_seconds(tf2), timeframe.in_seconds(tf3), timeframe.in_seconds(tf4), timeframe.in_seconds(tf5))
for i = 0 to 3
for j = i + 1 to 4
if array.get(durations, i) == array.get(durations, j)
runtime.error("Choose five different timeframe durations. Repeated durations must not receive extra votes.")
// HTF: previous completed source candle, delivered at the next source period.
// Chart TF: current state at chart close, otherwise previous completed state.
// LTF: last completed source candle inside this chart candle; if none exists yet,
// retain the last available sample and its timestamp. No aggregation or varip.
f_sample(simple string tf) =>
int sampledState = na
int sampledTime = na
var int lastLowerState = na
var int lastLowerTime = na
if tf == f_canonical(timeframe.period)
sampledState := chartClosedState
sampledTime := chartClosedTime
else if timeframe.in_seconds(tf) >= chartSeconds
[higherState, higherTime] = request.security(syminfo.tickerid, tf, f_closedPayload(),
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
sampledState := higherState
sampledTime := higherTime
else
[lowerStates, lowerCloses] = request.security_lower_tf(syminfo.tickerid, tf, [f_state(), time_close], ignore_invalid_timeframe=true)
// At the confirmed close, use the bar's own close time, as on historical bars.
int horizon = barstate.isrealtime and not barstate.isconfirmed ? timenow : time_close
int count = array.size(lowerStates)
if count > 0
for i = count - 1 to 0
int candidateTime = array.get(lowerCloses, i)
if not na(candidateTime) and candidateTime <= horizon
lastLowerState := array.get(lowerStates, i)
lastLowerTime := candidateTime
break
sampledState := lastLowerState
sampledTime := lastLowerTime
[sampledState, sampledTime]
[state1, stamp1] = f_sample(tf1)
[state2, stamp2] = f_sample(tf2)
[state3, stamp3] = f_sample(tf3)
[state4, stamp4] = f_sample(tf4)
[state5, stamp5] = f_sample(tf5)
array<int> states = array.from(state1, state2, state3, state4, state5)
array<int> stamps = array.from(stamp1, stamp2, stamp3, stamp4, stamp5)
array<string> timeframes = array.from(tf1, tf2, tf3, tf4, tf5)
array<int> secondsBySlot = array.from(timeframe.in_seconds(tf1), timeframe.in_seconds(tf2), timeframe.in_seconds(tf3), timeframe.in_seconds(tf4), timeframe.in_seconds(tf5))
int upVotes = 0
int downVotes = 0
int neutralVotes = 0
int missingVotes = 0
for state in states
if na(state)
missingVotes += 1
else if state == 1
upVotes += 1
else if state == -1
downVotes += 1
else
neutralVotes += 1
// Roles require two lower, this exact chart interval, and two higher intervals.
// Other Custom layouts and extreme Auto ranges keep five states and vote alerts.
bool contextLayout = timeframe.in_seconds(tf1) < timeframe.in_seconds(tf2) and timeframe.in_seconds(tf2) < chartSeconds and
tf3 == f_canonical(timeframe.period) and chartSeconds < timeframe.in_seconds(tf4) and timeframe.in_seconds(tf4) < timeframe.in_seconds(tf5)
// Codes: 0 missing, 1 split context, 2 chart conflict, 3 pullback, 4 aligned, 5 partial.
f_phase(int a, int b, int c, int d, int e, int slow, int order, int priceSide) =>
int phase = 0
if not na(a) and not na(b) and not na(c) and not na(d) and not na(e) and not na(slow) and not na(order) and not na(priceSide)
int context = d == e and d != 0 ? d : 0
if context == 0
phase := 1
else if slow != context or order != context
phase := 2
else if a == -context or b == -context or c == -context or priceSide == -context
phase := 3
else if a == context and b == context and c == context and priceSide == context
phase := 4
else
phase := 5
phase
int lineOrder = na(flow) or na(slowFlow) ? na : flow > slowFlow ? 1 : flow < slowFlow ? -1 : 0
int priceSide = na(close) or na(flow) ? na : close > flow ? 1 : close < flow ? -1 : 0
int phaseNow = contextLayout ? f_phase(state1, state2, state3, state4, state5, slowState, lineOrder, priceSide) : 0
int contextNow = not na(state4) and not na(state5) and state4 == state5 and state4 != 0 ? state4 : 0
var int watchedContext = 0
var bool pullbackObserved = false
var int confirmedPhase = 0
var int confirmedContext = 0
bool recoveryUp = false
bool recoveryDown = false
// Memory commits only at chart close; no intrabar event path or varip state.
if barstate.isconfirmed
if phaseNow <= 2 or contextNow != watchedContext
pullbackObserved := false
if phaseNow == 3
pullbackObserved := true
else if phaseNow == 4 and pullbackObserved
recoveryUp := contextNow == 1
recoveryDown := contextNow == -1
pullbackObserved := false
watchedContext := contextNow
confirmedContext := contextNow
confirmedPhase := recoveryUp or recoveryDown ? 6 : phaseNow
bool anyRecovery = recoveryUp or recoveryDown
// Confirmed chart turns ignore a neutral pause. Unavailable data resets memory.
var int lastDirection = 0
bool turnUp = false
bool turnDown = false
if barstate.isconfirmed
if na(chartState)
lastDirection := 0
else if chartState != 0
turnUp := chartState == 1 and lastDirection == -1
turnDown := chartState == -1 and lastDirection == 1
lastDirection := chartState
bool anyTurn = turnUp or turnDown
bool alignedUp = missingVotes == 0 and upVotes >= alignmentRequired
bool alignedDown = missingVotes == 0 and downVotes >= alignmentRequired
bool alignmentUpEvent = barstate.isconfirmed and alignedUp and not alignedUp[1]
bool alignmentDownEvent = barstate.isconfirmed and alignedDown and not alignedDown[1]
bool anyAlignmentEvent = alignmentUpEvent or alignmentDownEvent
// Price/curve crosses are independent of slope turns and MTF agreement.
// Equality on the preceding candle can lead to a cross; equality now cannot.
// Readiness on both candles suppresses artificial events at warm-up/recovery.
bool breakDataReady = not na(chartState) and not na(chartState[1]) and not na(close[1]) and not na(flow[1])
bool priceBreakUp = barstate.isconfirmed and breakDataReady and close > flow and close[1] <= flow[1]
bool priceBreakDown = barstate.isconfirmed and breakDataReady and close < flow and close[1] >= flow[1]
bool anyPriceBreak = priceBreakUp or priceBreakDown
// Raw alert fields come first and stay inside the first-20-plot placeholder limit.
plot(chartClosedState, "Confirmed Chart State", display=display.data_window, precision=0)
plot(upVotes, "Up Timeframes", display=display.data_window, precision=0)
plot(downVotes, "Down Timeframes", display=display.data_window, precision=0)
plot(neutralVotes, "Neutral Timeframes", display=display.data_window, precision=0)
plot(missingVotes, "Unavailable Timeframes", display=display.data_window, precision=0)
// PRICE OVERLAY: compact centered strokes with a separate background fill.
// Glow brightness follows the continuity of the curve's own direction.
// Nothing in this display block feeds filter values, MTF sampling or alerts.
f_glowContinuity(int state) =>
bool repeated = not na(state) and not na(state[1]) and state != 0 and state == state[1]
float continuity = ta.ema(repeated ? 1.0 : 0.0, 4)
continuity * continuity * (3.0 - 2.0 * continuity)
bool glowEnabled = glowMode != "Off"
bool strongGlow = glowMode == "Strong"
bool gradientReady = not na(chartState) and not na(slowState)
bool gradientEnabled = showSlowFlow and showGradientFill and gradientReady
bool fastAboveSlow = flow > slowFlow
color pairInk = fastAboveSlow ? upColor : downColor
int fillFade = fillIntensity == "Strong" ? 55 : fillIntensity == "Soft" ? 86 : 70
int fillPreviewFade = barstate.isconfirmed ? 0 : 10
color nearFastInk = gradientEnabled ? color.new(pairInk, math.min(98, fillFade + fillPreviewFade)) : na
color nearSlowInk = gradientEnabled ? color.new(pairInk, 100) : na
float gradientTop = math.max(flow, slowFlow)
float gradientBottom = math.min(flow, slowFlow)
// Exact selected hues: opacity carries presentation changes; no gray color blend.
bool fastDirectional = not na(chartState) and chartState != 0
bool slowDirectional = not na(slowState) and slowState != 0
color flowInk = not fastDirectional ? neutralColor : chartState == 1 ? upColor : downColor
color slowInk = not slowDirectional ? neutralColor : slowState == 1 ? upColor : downColor
float fastContinuity = f_glowContinuity(chartState)
float slowContinuity = f_glowContinuity(slowState)
float opacityFloor = strongGlow ? 0.30 : 0.16
float opacityRange = strongGlow ? 0.22 : 0.12
float openCandleFactor = barstate.isconfirmed ? 1.0 : 0.80
float fastRimOpacity = (opacityFloor + opacityRange * fastContinuity) * openCandleFactor * (fastDirectional ? 1.0 : 0.55)
float slowRimOpacity = (opacityFloor + opacityRange * slowContinuity) * openCandleFactor * (slowDirectional ? 0.90 : 0.55)
float fastHaloOpacity = fastRimOpacity * 0.45
float slowHaloOpacity = slowRimOpacity * 0.45
int corePreviewFade = barstate.isconfirmed ? 0 : 18
// All halos precede all cores. Fast's core stays foremost at an exact overlap.
plot(showSlowFlow and glowEnabled ? slowFlow : na, "Slow outer glow",
color=color.new(slowInk, 100.0 * (1.0 - slowHaloOpacity)), linewidth=strongGlow ? 12 : 9,
style=plot.style_linebr, display=display.pane, editable=false, force_overlay=true)
plot(glowEnabled ? flow : na, "Fast outer glow",
color=color.new(flowInk, 100.0 * (1.0 - fastHaloOpacity)), linewidth=strongGlow ? 12 : 9,
style=plot.style_linebr, display=display.pane, editable=false, force_overlay=true)
plot(showSlowFlow and glowEnabled ? slowFlow : na, "Slow inner glow",
color=color.new(slowInk, 100.0 * (1.0 - slowRimOpacity)), linewidth=strongGlow ? 6 : 4,
style=plot.style_linebr, display=display.pane, editable=false, force_overlay=true)
plot(glowEnabled ? flow : na, "Fast inner glow",
color=color.new(flowInk, 100.0 * (1.0 - fastRimOpacity)), linewidth=strongGlow ? 6 : 4,
style=plot.style_linebr, display=display.pane, editable=false, force_overlay=true)
slowPlot = plot(showSlowFlow ? slowFlow : na, "Slow Flow", color=color.new(slowInk, corePreviewFade), linewidth=2,
style=plot.style_linebr, display=display.pane, force_overlay=true)
corePlot = plot(flow, "Fast Flow", color=color.new(flowInk, corePreviewFade), linewidth=2,
style=plot.style_linebr, display=display.pane, force_overlay=true)
// Standard z-index renders this inter-line fill beneath all center strokes.
fill(corePlot, slowPlot, gradientTop, gradientBottom, fastAboveSlow ? nearFastInk : nearSlowInk,
fastAboveSlow ? nearSlowInk : nearFastInk, title="Fast / Slow gradient", fillgaps=false)
float turnValue = showTurns and anyTurn ? flow : na
color turnInk = turnUp ? upColor : downColor
plot(glowEnabled ? turnValue : na, "Turn halo", color=color.new(turnInk, strongGlow ? 74 : 86), linewidth=strongGlow ? 14 : 10,
style=plot.style_circles, display=display.pane, force_overlay=true)
plot(turnValue, "Confirmed turn dot", color=turnInk, linewidth=4,
style=plot.style_circles, display=display.pane, force_overlay=true)
// Chart-only bar shading. No value here feeds the model, sampling or events.
float barSlowAgreement = not na(slowState) and slowState == chartState ? 1.0 : 0.0
float barOrderAgreement = not na(lineOrder) and lineOrder == chartState ? 1.0 : 0.0
float barSupport = (barSlowAgreement + barOrderAgreement) * 0.5
float barBlend = 0.25 + 0.75 * barSupport * fastContinuity
color barGradientInk = fastDirectional ? color.from_gradient(barBlend, 0.0, 1.0, neutralColor, flowInk) : neutralColor
color barSelectedInk = barColorMode == "Gradient" ? barGradientInk : flowInk
color candleInk = barColorMode != "Off" and not na(chartState) ? color.new(barSelectedInk, corePreviewFade) : na
barcolor(candleInk, title="Flow Bar Colors", editable=false)
// Small price-break triangles sit beside their actual closing candle.
plotshape(showPriceBreaks and priceBreakUp, title="Price Break Up", style=shape.triangleup,
location=location.belowbar, color=upColor, size=size.tiny, display=display.pane, force_overlay=true)
plotshape(showPriceBreaks and priceBreakDown, title="Price Break Down", style=shape.triangledown,
location=location.abovebar, color=downColor, size=size.tiny, display=display.pane, force_overlay=true)
// Five directional tiles; neutral and missing are different states.
string tablePosition = switch dashboardPosition
"Bottom Left" => position.bottom_left
"Top Right" => position.top_right
"Top Left" => position.top_left
=> position.bottom_right
int textSize = dashboardSize == "Large" ? 14 : dashboardSize == "Small" ? 10 : 12
int arrowSize = dashboardSize == "Large" ? 20 : dashboardSize == "Small" ? 14 : 17
float tileWidth = dashboardSize == "Large" ? 3.4 : dashboardSize == "Small" ? 2.2 : 2.8
float tileHeight = dashboardSize == "Large" ? 4.0 : dashboardSize == "Small" ? 2.6 : 3.3
var table dashboard = table.new(tablePosition, 5, 6, bgcolor=color.new(chart.bg_color, 15), border_width=0, force_overlay=true)
if barstate.isfirst
table.merge_cells(dashboard, 0, 0, 4, 0)
table.merge_cells(dashboard, 0, 4, 4, 4)
table.merge_cells(dashboard, 0, 5, 4, 5)
if barstate.islast
if showDashboard
string summary = missingVotes > 0 ? "Data " + str.tostring(5 - missingVotes) + "/5 · " + str.tostring(upVotes) + "↑ " + str.tostring(downVotes) + "↓" :
upVotes >= 3 ? "↑ " + str.tostring(upVotes) + "/5 up" :
downVotes >= 3 ? "↓ " + str.tostring(downVotes) + "/5 down" :
neutralVotes >= 3 ? "→ " + str.tostring(neutralVotes) + "/5 neutral" : "MIXED"
color summaryInk = missingVotes > 0 ? chart.fg_color : upVotes >= 3 ? upColor : downVotes >= 3 ? downColor : neutralColor
table.cell(dashboard, 0, 0, syminfo.ticker + " " + summary, text_color=summaryInk, text_size=textSize,
tooltip="Each of the five timeframes has one vote. A majority describes directional agreement, not a probability.")
for i = 0 to 4
int state = array.get(states, i)
int closedAt = array.get(stamps, i)
string tf = array.get(timeframes, i)
string arrow = na(state) ? "—" : state == 1 ? "↑" : state == -1 ? "↓" : "→"
color tileInk = na(state) or state == 0 ? neutralColor : state == 1 ? upColor : downColor
string stateText = na(state) ? "Filter data unavailable" :
state == 1 ? "Up" : state == -1 ? "Down" : "Neutral: no filtered change"
string timeText = na(closedAt) ? "No completed source candle yet" :
"Last source candle used closed: " + str.format_time(closedAt, "yyyy-MM-dd HH:mm", syminfo.timezone)
string tileTip = f_tfText(tf) + " · " + stateText + "\n" + timeText + "\n" +
"Time uses exchange timezone. Lower timeframes show the last available closed intrabar; empty new intervals retain that sample and its timestamp."
table.cell(dashboard, i, 1, arrow, width=tileWidth, height=tileHeight, text_size=arrowSize, text_color=na(state) ? chart.fg_color : color.white,
bgcolor=color.new(tileInk, na(state) ? 75 : 12), tooltip=tileTip)
int tileSeconds = array.get(secondsBySlot, i)
string role = contextLayout ? (i < 2 ? "Timing" : i == 2 ? "Chart" : "Context") :
tileSeconds < chartSeconds ? "Lower" : tileSeconds > chartSeconds ? "Higher" : "Chart span"
table.cell(dashboard, i, 3, role, text_size=math.max(8, textSize - 2), text_color=color.new(chart.fg_color, 25), tooltip=tileTip)
table.cell(dashboard, i, 2, f_tfText(tf), text_size=textSize, text_color=chart.fg_color, tooltip=tileTip)
string contextText = confirmedPhase == 0 ? "Waiting for data" : confirmedPhase == 1 ? "CONTEXT SPLIT" :
confirmedPhase == 2 ? "CHART CONFLICT" : confirmedPhase == 3 ? "PULLBACK" : confirmedPhase == 4 ? "ALIGNED" : confirmedPhase == 6 ? "RECOVERY" : "PARTIAL"
string contextPrefix = confirmedContext == 1 ? "UP · " : confirmedContext == -1 ? "DOWN · " : ""
color contextInk = confirmedPhase <= 2 ? neutralColor : confirmedContext == 1 ? upColor : downColor
table.cell(dashboard, 0, 4, showContext ? (contextLayout ? contextPrefix + contextText : "Context: chart-centered layout required") : "",
text_color=contextInk, text_size=textSize,
tooltip="Phase uses the last chart close, including the completed-candle MTF states available at that time. It is separate from the live tile count. CONTEXT SPLIT: the two higher states disagree or one is neutral. CHART CONFLICT: chart Slow slope or Fast/Slow order does not support the context. PULLBACK means an observed counter-move with higher context and chart Slow support intact. PARTIAL: nothing opposes the context, but not every lower/chart state and price agree with it yet. ALIGNED: all five states and price agree. RECOVERY requires a prior observed pullback and subsequent full directional agreement with price beyond Fast. No recovery is inferred from an already aligned initial state. Missing data or lost support clears memory. Hiding Slow Flow does not disable its use here.")
table.cell(dashboard, 0, 5, barstate.isconfirmed ? "Curve & MTF: closed" : "Curve: LIVE · MTF: closed",
text_size=math.max(8, textSize - 2), text_color=color.new(chart.fg_color, 25),
tooltip="The open-candle curve is provisional. MTF states use completed source candles. Higher-timeframe updates become available at the next source interval. All alerts wait for chart candle close.")
else
table.clear(dashboard, 0, 0, 4, 5)
alertcondition(turnUp, "Chart Trend Turn Up", "WizTrader Trend Flow MTF | Confirmed chart turn UP | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(turnDown, "Chart Trend Turn Down", "WizTrader Trend Flow MTF | Confirmed chart turn DOWN | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(anyTurn, "Any Chart Trend Turn", "WizTrader Trend Flow MTF | Confirmed chart trend turn | {{ticker}} | TF {{interval}} | State {{plot(\"Confirmed Chart State\")}} | Candle close {{close}}")
alertcondition(alignmentUpEvent, "MTF Alignment Up", "WizTrader Trend Flow MTF | Up alignment threshold newly met at chart close | {{ticker}} | Up {{plot(\"Up Timeframes\")}}/5 | Down {{plot(\"Down Timeframes\")}}/5 | Candle close {{close}}")
alertcondition(alignmentDownEvent, "MTF Alignment Down", "WizTrader Trend Flow MTF | Down alignment threshold newly met at chart close | {{ticker}} | Down {{plot(\"Down Timeframes\")}}/5 | Up {{plot(\"Up Timeframes\")}}/5 | Candle close {{close}}")
alertcondition(anyAlignmentEvent, "Any MTF Alignment", "WizTrader Trend Flow MTF | Directional alignment threshold newly met at chart close | {{ticker}} | Up {{plot(\"Up Timeframes\")}}/5 | Down {{plot(\"Down Timeframes\")}}/5 | Neutral {{plot(\"Neutral Timeframes\")}}/5 | Candle close {{close}}")
alertcondition(priceBreakUp, "Price Break Up", "WizTrader Trend Flow MTF | Confirmed close crossed ABOVE Fast Flow | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(priceBreakDown, "Price Break Down", "WizTrader Trend Flow MTF | Confirmed close crossed BELOW Fast Flow | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(anyPriceBreak, "Any Price Break", "WizTrader Trend Flow MTF | Confirmed close crossed Fast Flow | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(recoveryUp, "Context Recovery Up", "WizTrader Trend Flow MTF | UP context recovery after a previously observed pullback | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(recoveryDown, "Context Recovery Down", "WizTrader Trend Flow MTF | DOWN context recovery after a previously observed pullback | {{ticker}} | TF {{interval}} | Candle close {{close}}")
alertcondition(anyRecovery, "Any Context Recovery", "WizTrader Trend Flow MTF | Context recovery after a previously observed pullback | {{ticker}} | TF {{interval}} | State {{plot(\"Confirmed Chart State\")}} | Candle close {{close}}")