//@version=6
// ============================================================================
// DELTA BREAK & RETEST -- STAGE 4: MTF BIAS STACK
// ----------------------------------------------------------------------------
// Per the build spec, Section 9, Stage 4: "MTF bias stack. Plot 4H bias and
// 1H trendOK as a background colour. Verify no repaint."
//
// Implements Section 2's timeframe hierarchy, top two links only:
// 4H -- bias / theater authority: bias in {LONG_ONLY, SHORT_ONLY, NO_TRADE}
// 1H -- trend confirmation: trendOK in {true, false}
// The 15m (setup/POI/break) and 5m (execution/retest/trigger) links come in
// Stages 5-6. STILL NO TRADING LOGIC of any kind here -- this plots two
// context reads, nothing else.
//
// 4H BIAS (Section 2):
// Structure: last confirmed 4H swing sequence. HH+HL = up, LH+LL = down,
// anything else = mixed/neutral.
// Slow filter: 4H close vs 4H 50 EMA, and that EMA's slope over the last
// 5 (4H) bars.
// BOTH must agree -- disagreement is NO_TRADE, not a coin flip, per spec.
//
// 1H TREND CONFIRMATION (Section 2):
// ADX(14) >= 20, EMA(21) vs EMA(50) stacked in the bias direction,
// Kaufman Efficiency Ratio(10) >= 0.30 (the spec's primary chop gate).
//
// NON-REPAINT DESIGN (the spec's explicit instruction to verify):
// Swing highs/lows use ta.pivothigh()/pivotlow(), which are structurally
// non-repainting -- a pivot only resolves `right` bars after the fact and
// never changes once confirmed. Pulled via request.security() at the
// library default lookahead = barmerge.lookahead_off (no forward
// peeking). gaps_off (the request.security default) forward-fills the
// last CONFIRMED value across subsequent lower-timeframe bars, which is
// exactly what lets a single pulled series behave as "the latest
// confirmed swing point," continuously available, without hand-rolled
// history tracking beyond detecting when that forward-filled value
// steps to a new one.
// HOW TO VERIFY BY EYE (Pine has no automated repaint test): the "Bias/
// TrendOK Change Log" on the dashboard records the bar index each time
// either value flips. Reload the script later (or on a different
// session/device) and confirm the same historical transitions still show
// the same bar index and value. A repainting MTF read would show a
// different bar index or value for the same historical transition on
// reload; this design shouldn't.
// ============================================================================
indicator(title = "Delta Break & Retest - Stage 4 MTF Bias Stack", shorttitle = "DBR Stage4", overlay = true)
// ============================================================================
// INPUTS
// ============================================================================
string biasTimeframeInput = input.timeframe("240", "4H Bias Timeframe", group = "4H Bias")
int pivotLeftInput = input.int(3, "Swing Pivot Left Bars", minval = 1, maxval = 20, group = "4H Bias")
int pivotRightInput = input.int(3, "Swing Pivot Right Bars", minval = 1, maxval = 20, group = "4H Bias", tooltip = "A pivot only confirms this many bars after it forms -- higher values are slower but more reliable, and this delay is exactly what keeps swing detection non-repainting.")
int biasEmaLengthInput = input.int(50, "4H EMA Length", minval = 2, group = "4H Bias")
int biasSlopeLookbackInput = input.int(5, "4H EMA Slope Lookback (Bars)", minval = 1, maxval = 50, group = "4H Bias")
string trendTimeframeInput = input.timeframe("60", "1H Trend Timeframe", group = "1H Trend Confirmation")
int adxLengthInput = input.int(14, "1H ADX / DI Length", minval = 1, group = "1H Trend Confirmation")
float adxMinimumInput = input.float(20.0, "1H Minimum ADX", minval = 0, step = 0.5, group = "1H Trend Confirmation")
int fastEmaInput = input.int(21, "1H Fast EMA", minval = 1, group = "1H Trend Confirmation")
int slowEmaInput = input.int(50, "1H Slow EMA", minval = 2, group = "1H Trend Confirmation")
int erLengthInput = input.int(10, "1H Efficiency Ratio Length", minval = 2, group = "1H Trend Confirmation")
float erMinimumInput = input.float(0.30, "1H Minimum Efficiency Ratio", minval = 0, maxval = 1, step = 0.05, group = "1H Trend Confirmation")
bool showBiasBackgroundInput = input.bool(true, "Show 4H Bias Background", group = "Display")
bool showTrendBarColorInput = input.bool(true, "Show 1H TrendOK Bar Color", group = "Display")
// ============================================================================
// 4H CONTEXT -- one wrapper function so request.security only needs a
// single call; ta.ema() is computed once per value rather than repeated
// inline across a tuple literal.
// ============================================================================
// FIXED (round 1): the original version computed ta.pivothigh()/pivotlow()
// inside a function pulled with lookahead=barmerge.lookahead_off, then
// hand-tracked "latest vs. previous confirmed pivot" via var state watching
// the pulled series change -- that combination never produced a real value
// through request.security in practice (confirmed empirically: 0 pivot
// updates seen across months of fully-loaded 4H history, Replay ruled out
// as the cause). Replaced with the pattern proven working elsewhere in this
// repo (MTF_Second_Flip_Continuation_v1_2.pine's f_structureBias):
// ta.valuewhen(not na(pivot), pivot, N) computed natively inside the
// function, pulled with lookahead=barmerge.lookahead_on plus a one-bar-back
// offset.
//
// FIXED (round 2, CE10123): that reference function returns a SINGLE value,
// so f_structureBias()[1] is valid -- the [] history-reference operator can
// only be applied to a single series, not to a tuple. This function returns
// SEVEN values, so f_get4hContext()[1] is invalid ("operator SQBR" cannot
// take a tuple argument). Fix: apply the [1] offset to each value
// INDIVIDUALLY on the function's own last line, inside the function (still
// evaluated in the pulled HTF context), and pass the tuple to
// request.security with no outer [1].
f_get4hContext() =>
float ph = ta.pivothigh(high, pivotLeftInput, pivotRightInput)
float pl = ta.pivotlow(low, pivotLeftInput, pivotRightInput)
float latestHigh = ta.valuewhen(not na(ph), ph, 0)
float previousHigh = ta.valuewhen(not na(ph), ph, 1)
float latestLow = ta.valuewhen(not na(pl), pl, 0)
float previousLow = ta.valuewhen(not na(pl), pl, 1)
float ema = ta.ema(close, biasEmaLengthInput)
bool aboveEma = close > ema
bool slopeUp = ema > ema[biasSlopeLookbackInput]
bool slopeDown = ema < ema[biasSlopeLookbackInput]
[latestHigh[1], previousHigh[1], latestLow[1], previousLow[1], aboveEma[1], slopeUp[1], slopeDown[1]]
[lastPivotHigh, prevPivotHigh, lastPivotLow, prevPivotLow, closeAboveEma4h, emaSlopeUp4h, emaSlopeDown4h] = request.security(syminfo.tickerid, biasTimeframeInput, f_get4hContext(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
// ============================================================================
// 4H STRUCTURE -- latest vs. previous confirmed pivot, both now supplied
// directly by ta.valuewhen() inside f_get4hContext(); no local state to
// track here at all.
// ============================================================================
bool haveEnoughPivots = not na(lastPivotHigh) and not na(prevPivotHigh) and not na(lastPivotLow) and not na(prevPivotLow)
bool higherHigh = haveEnoughPivots and lastPivotHigh > prevPivotHigh
bool lowerHigh = haveEnoughPivots and lastPivotHigh < prevPivotHigh
bool higherLow = haveEnoughPivots and lastPivotLow > prevPivotLow
bool lowerLow = haveEnoughPivots and lastPivotLow < prevPivotLow
bool structureUp = higherHigh and higherLow
bool structureDown = lowerHigh and lowerLow
bool slowFilterUp = closeAboveEma4h and emaSlopeUp4h
bool slowFilterDown = (not closeAboveEma4h) and emaSlopeDown4h
// ============================================================================
// 4H BIAS -- structure AND slow filter must both agree; disagreement is
// NO_TRADE, not a coin flip, per spec.
// ============================================================================
string bias = structureUp and slowFilterUp ? "LONG_ONLY" : structureDown and slowFilterDown ? "SHORT_ONLY" : "NO_TRADE"
// ============================================================================
// 1H CONTEXT -- same one-function-per-security-call pattern. ta.dmi()
// itself returns a 3-value tuple, which can't be nested as a single slot
// inside another tuple literal, so it's destructured LOCALLY inside this
// function and only the single ADX value is passed onward.
// ============================================================================
f_efficiencyRatio(int length) =>
float netMove = math.abs(close - close[length])
float sumMoves = 0.0
for i = 0 to length - 1
sumMoves += math.abs(close[i] - close[i + 1])
sumMoves > 0 ? netMove / sumMoves : 0.0
f_get1hContext() =>
[plusDi, minusDi, adx] = ta.dmi(adxLengthInput, adxLengthInput)
float emaFast = ta.ema(close, fastEmaInput)
float emaSlow = ta.ema(close, slowEmaInput)
float er = f_efficiencyRatio(erLengthInput)
[adx[1], emaFast[1], emaSlow[1], er[1]]
// Same safe MTF idiom as the 4H pull, applied here too for consistency --
// this one already worked fine under the old lookahead_off (ADX/EMA/ER all
// read correctly in testing), but there's no reason for the 4H and 1H
// pulls to use two different lookahead strategies once one of them is
// known to be the more robust choice. Offset is applied per-value INSIDE
// the function (see f_get4hContext's comment) since this also returns a
// tuple, not a single series -- request.security(...)[1] on the outer call
// is invalid here (CE10123).
[adx1h, emaFast1h, emaSlow1h, er1h] = request.security(syminfo.tickerid, trendTimeframeInput, f_get1hContext(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
// ============================================================================
// 1H TREND CONFIRMATION
// ============================================================================
bool adxOk = adx1h >= adxMinimumInput
// Raw stack direction, independent of bias -- used for the dashboard so it
// shows what the EMAs are actually doing rather than a bias-gated "NOT
// ALIGNED" that fires just because bias is NO_TRADE.
string emaStackRaw = emaFast1h > emaSlow1h ? "BULLISH" : emaFast1h < emaSlow1h ? "BEARISH" : "FLAT"
bool emaStackOk = bias == "LONG_ONLY" ? emaFast1h > emaSlow1h : bias == "SHORT_ONLY" ? emaFast1h < emaSlow1h : false
bool erOk = er1h >= erMinimumInput
bool trendOK = bias != "NO_TRADE" and adxOk and emaStackOk and erOk
// ============================================================================
// CHANGE LOG -- for the spec's explicit "verify no repaint" instruction.
// Records only actual transitions (not every bar), so reloading later and
// comparing the same historical bar indices is a direct repaint check.
// ============================================================================
var string lastLoggedBias = ""
var bool lastLoggedTrendOK = false
var array<string> changeLog = array.new_string()
if barstate.isconfirmed
if bias != lastLoggedBias
array.unshift(changeLog, "bar" + str.tostring(bar_index) + " BIAS -> " + bias)
if array.size(changeLog) > 8
array.pop(changeLog)
lastLoggedBias := bias
if trendOK != lastLoggedTrendOK
array.unshift(changeLog, "bar" + str.tostring(bar_index) + " TRENDOK -> " + str.tostring(trendOK))
if array.size(changeLog) > 8
array.pop(changeLog)
lastLoggedTrendOK := trendOK
// ============================================================================
// PLOTS -- background = 4H bias, bar color = 1H trendOK confirming it
// ============================================================================
color biasBg = bias == "LONG_ONLY" ? color.new(color.green, 85) : bias == "SHORT_ONLY" ? color.new(color.red, 85) : color.new(color.gray, 92)
bgcolor(showBiasBackgroundInput ? biasBg : na, title = "4H Bias Background")
color trendBarColor = not trendOK ? na : bias == "LONG_ONLY" ? color.new(color.lime, 20) : bias == "SHORT_ONLY" ? color.new(color.red, 20) : na
barcolor(showTrendBarColorInput ? trendBarColor : na, title = "1H TrendOK Bar Color")
plot(lastPivotHigh, title = "4H Latest Confirmed Pivot High", color = color.new(color.orange, 60), style = plot.style_circles, display = display.data_window)
plot(prevPivotHigh, title = "4H Previous Confirmed Pivot High", color = color.new(color.orange, 80), style = plot.style_circles, display = display.data_window)
plot(lastPivotLow, title = "4H Latest Confirmed Pivot Low", color = color.new(color.blue, 60), style = plot.style_circles, display = display.data_window)
plot(prevPivotLow, title = "4H Previous Confirmed Pivot Low", color = color.new(color.blue, 80), style = plot.style_circles, display = display.data_window)
// ============================================================================
// DASHBOARD
// ============================================================================
var table statusTable = table.new(position.top_right, 2, 15, bgcolor = color.new(color.rgb(15, 20, 27), 10), border_width = 1)
if barstate.islast
table.cell(statusTable, 0, 0, "STAGE 4 MTF BIAS STACK", text_color = color.white, bgcolor = color.rgb(22, 52, 86))
table.cell(statusTable, 1, 0, "", text_color = color.white, bgcolor = color.rgb(22, 52, 86))
table.cell(statusTable, 0, 1, "4H Bias", text_color = color.white)
table.cell(statusTable, 1, 1, bias, text_color = bias == "LONG_ONLY" ? color.lime : bias == "SHORT_ONLY" ? color.red : color.gray)
table.cell(statusTable, 0, 2, "4H Structure", text_color = color.white)
table.cell(statusTable, 1, 2, structureUp ? "HH + HL" : structureDown ? "LH + LL" : "MIXED", text_color = color.white)
// Shows directly whether structure has enough confirmed swings to make
// any call at all -- MIXED can mean "genuinely no clean trend" or "not
// enough 4H history yet" (e.g. early in a Replay session, which only
// provides bars played back so far, not the full chart history); this
// row tells you which one you're looking at instead of leaving it to
// guesswork.
table.cell(statusTable, 0, 3, "4H Pivots Ready", text_color = color.white)
table.cell(statusTable, 1, 3, haveEnoughPivots ? "YES" : "NO (insufficient 4H history)", text_color = haveEnoughPivots ? color.lime : color.orange)
table.cell(statusTable, 0, 4, "4H Price vs EMA / Slope", text_color = color.white)
table.cell(statusTable, 1, 4, (closeAboveEma4h ? "ABOVE" : "BELOW") + " / " + (emaSlopeUp4h ? "UP" : emaSlopeDown4h ? "DOWN" : "FLAT"), text_color = color.white)
table.cell(statusTable, 0, 5, "1H TrendOK", text_color = color.white)
table.cell(statusTable, 1, 5, trendOK ? "TRUE" : "FALSE", text_color = trendOK ? color.lime : color.gray)
table.cell(statusTable, 0, 6, "1H ADX", text_color = color.white)
table.cell(statusTable, 1, 6, str.tostring(adx1h, "#.0") + (adxOk ? " OK" : " LOW"), text_color = adxOk ? color.lime : color.gray)
// Raw direction (not bias-gated) -- shows what the EMAs are actually
// doing; color still reflects whether that agrees with the current
// bias (emaStackOk), so a mismatch reads as gray even if the raw
// direction itself looks decisive.
table.cell(statusTable, 0, 7, "1H EMA Stack", text_color = color.white)
table.cell(statusTable, 1, 7, emaStackRaw, text_color = emaStackOk ? color.lime : color.gray)
table.cell(statusTable, 0, 8, "1H Efficiency Ratio", text_color = color.white)
table.cell(statusTable, 1, 8, str.tostring(er1h, "#.##") + (erOk ? " OK" : " CHOP"), text_color = erOk ? color.lime : color.gray)
table.cell(statusTable, 0, 9, "Change Log", text_color = color.white, bgcolor = color.rgb(22, 52, 86))
table.cell(statusTable, 1, 9, "", text_color = color.white, bgcolor = color.rgb(22, 52, 86))
int maxLogRows = 5
for r = 0 to maxLogRows - 1
int tableRow = 10 + r
if r < array.size(changeLog)
table.cell(statusTable, 0, tableRow, array.get(changeLog, r), text_color = color.white, text_halign = text.align_left)
table.cell(statusTable, 1, tableRow, "", text_color = color.white)
else
table.cell(statusTable, 0, tableRow, "", text_color = color.white)
table.cell(statusTable, 1, tableRow, "", text_color = color.white)
// ============================================================================
// DATA WINDOW
// ============================================================================
plot(adx1h, title = "1H ADX", display = display.data_window)
plot(er1h, title = "1H Efficiency Ratio", display = display.data_window)
plot(emaFast1h, title = "1H EMA Fast", display = display.data_window)
plot(emaSlow1h, title = "1H EMA Slow", display = display.data_window)
Overview
A 4-hour bias comes from swing structure agreeing with the close versus a 50 EMA and its slope, and a 1-hour trend check requires ADX, stacked fast and slow EMAs and an efficiency ratio above a minimum. Bias shows as a background colour and the trend check as bar colour. It pulls higher timeframe data, and a change log helps check for repainting.
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
4H Bias Timeframe
timeframe
240
biasTimeframeInput
Swing Pivot Left Bars
int
3
pivotLeftInput
Swing Pivot Right Bars
int
3
pivotRightInput
4H EMA Length
int
50
biasEmaLengthInput
4H EMA Slope Lookback (Bars)
int
5
biasSlopeLookbackInput
1H Trend Timeframe
timeframe
60
trendTimeframeInput
1H ADX / DI Length
int
14
adxLengthInput
1H Minimum ADX
float
20.0
adxMinimumInput
1H Fast EMA
int
21
fastEmaInput
1H Slow EMA
int
50
slowEmaInput
1H Efficiency Ratio Length
int
10
erLengthInput
1H Minimum Efficiency Ratio
float
0.30
erMinimumInput
Show all 14 settings
Setting
Type
Default
Variable
Show 4H Bias Background
bool
true
showBiasBackgroundInput
Show 1H TrendOK Bar Color
bool
true
showTrendBarColorInput
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.
The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec
This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult
This indicator classifies each bar as bull, bear, or sideways from a rolling log return compared with adjustable percentage thresholds. It paints a regime ribbon on the price chart, shows a current-regime banner, and labels state changes after a minimum hold.
This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab
This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos
All Candlestick Patterns detects and highlights a wide range of bullish, bearish, and neutral candlestick patterns directly on the price chart. It features optional trend filtering using either a 50-period simple moving average or a combination of 50-period an