本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Narrative OB | Context + Inducement v5.1", shorttitle = "HTF OB v5.1", overlay = true, max_bars_back = 500, max_boxes_count = 160, max_lines_count = 300, max_labels_count = 100)
// Higher-timeframe OBs and major structure only. No execution entry model.
// BOS is a strict native candle close beyond a locked structural wick level.
// ATR, displacement, inducement and OB acceptance NEVER gate a BOS.
// In a trend, internal counter-swings cannot move the protected structural edge.
// A continuation updates protection only after a close breaks the external swing.
// Confirmed pivots seed/lock external swings; right-side confirmation adds delay.
// BOS and wick rules are preserved from v3. OB selection is now separate:
// 1. Cache qualified hourly departure bases when observable, before any BOS.
// 2. Keep their original identities across structural breaks and retracements.
// 3. At BOS, search sources already known before the breaking leg's origin.
// 4. Prefer an interacted-with parent, then the most recent eligible left source.
// New bases formed inside the breaking leg cannot stand in for missing context.
// Source scoring remains a qualification filter, not the context ranking rule.
// Selection uses only data known at BOS; no successful future return is required.
// Wick refinement uses closed source-TF candles after the base, never the base
// itself. Visible refinements create a new segment at first availability.
// Initial origin tracing is retrospective; dotted vertical = first availability.
// The optional 5m feed supplies source-formation inducement evidence only.
// No 5m BOS, entry zones, narrative, or trade/target model is calculated.
// V5.1 chooses the highest unswept internal high in supply (lowest low in
// demand). Source/base/launch candles are excluded. A lower internal pivot
// cannot replace that outer reference. The normal reclaim/invalidation rules
// are unchanged. Markers use actual chart-bar spacing across session gaps.
// V5 keeps the v4 structure engine, source qualification, context selection,
// and wick rules. The new layer classifies returns into those parent sources.
// A confirmed native-TF swing taken AGAINST its parent's direction is pending
// until a strict native close reclaims that level. Parent invalidation wins.
// Pending internal breaks do not override the parent; outside-parent BOS is intact.
// Hidden sources retain sweeps, but marks appear ONLY for selected parent OBs.
// An X traces the reference/take interval retrospectively. Its tooltip records
// reclaim and first-display times. Delayed parent selection cannot backdate alerts.
// This return confluence is additional to mandatory source-formation inducement.
// Synthetic helper checks are not TradingView compilation or market validation.
string G_S = "01 | Higher-timeframe structure"
string contextTF = input.timeframe("60", "Structure and OB timeframe", options = ["15", "30", "60", "240", "1D"], group = G_S)
int swingLength = input.int(3, "Confirmed swing width", minval = 1, maxval = 12, group = G_S, tooltip = "Bars on each side of a pivot. Internal pivots cannot move a protected major level. A strict close beyond that level confirms BOS; there is no ATR or tick buffer.")
int bosHistory = input.int(8, "Recent BOS lines", minval = 1, maxval = 20, group = G_S)
bool showLevels = input.bool(false, "Show current structural references", group = G_S)
string G_O = "02 | Hourly source memory"
int memoryCapacity = input.int(160, "Hidden context source capacity", minval = 20, maxval = 400, group = G_O, tooltip = "Qualified hourly sources are retained across BOS events. Only selected context is drawn. Age, invalidation and this cap limit retained history.")
int sourceScan = input.int(10, "Base search at departure", minval = 3, maxval = 24, group = G_O)
int baseBars = input.int(3, "Maximum adjacent base candles", minval = 1, maxval = 5, group = G_O)
int liquidityLength = input.int(4, "Internal liquidity lookback", minval = 2, maxval = 12, group = G_O)
int liquidityWindow = input.int(6, "Liquidity-to-origin allowance", minval = 0, maxval = 16, group = G_O)
string liquidityMode = input.string("Internal take", "Mandatory inducement", options = ["Internal take", "Take and reclaim"], group = G_O)
bool useEvidence = input.bool(true, "Use 5m source-formation evidence", group = G_O, tooltip = "Retains v2's supplemental inducement evidence inside the original hourly base/departure window. This is not a lower-timeframe entry model.")
float minimumDeparture = input.float(1.2, "OB departure / source ATR", minval = 0.4, maxval = 5.0, step = 0.1, group = G_O)
float minimumBody = input.float(0.55, "OB directional body / ATR", minval = 0.1, maxval = 2.0, step = 0.05, group = G_O)
float minimumEfficiency = input.float(0.45, "OB path efficiency", minval = 0.1, maxval = 0.95, step = 0.05, group = G_O)
float maximumWidth = input.float(2.2, "Maximum OB width / source ATR", minval = 0.3, maxval = 5.0, step = 0.1, group = G_O)
int minimumScore = input.int(70, "Minimum OB score", minval = 50, maxval = 95, group = G_O, tooltip = "Selection score, not probability. These filters affect OBs only. A BOS can print with no qualifying OB.")
string G_W = "03 | Wick mitigation"
string wickRule = input.string("Reach wick tip", "Wick counts as mitigated on", options = ["Reach wick tip", "Enter wick"], group = G_W, tooltip = "Reach wick tip: a later closed source-TF candle trades at the original high/low. Enter wick: any overlap with the wick's interior. A consumed upper wick trims to body high; lower wick trims to body low; both leaves the body. The source candle cannot mitigate itself.")
int perSide = input.int(3, "Recent context OBs per side", minval = 1, maxval = 6, group = G_W)
int archiveCount = input.int(8, "Retired OBs to retain", minval = 0, maxval = 20, group = G_W)
int zoneLifetime = input.int(350, "OB expiry in source bars", minval = 30, maxval = 1500, group = G_W)
string G_V = "04 | Appearance"
color supplyColor = input.color(#8798C1, "Supply", group = G_V)
color demandColor = input.color(#75A9A0, "Demand", group = G_V)
int fillTransparency = input.int(86, "Fill transparency", minval = 60, maxval = 98, group = G_V)
bool showMidpoint = input.bool(true, "OB midpoint", group = G_V)
bool traceOrigin = input.bool(true, "Trace initial OB to source", group = G_V)
bool markConfirmation = input.bool(true, "Mark initial availability", group = G_V)
int projectBars = input.int(10, "Projection in chart bars", minval = 2, maxval = 80, group = G_V)
string G_I = "05 | Inducement inside parent OBs"
bool showInducement = input.bool(true, "Mark hourly return inducement", group = G_I)
int inducementWidth = input.int(3, "Hourly liquidity swing width", minval = 1, maxval = 12, group = G_I, tooltip = "Native structure-TF pivots only. Bars on each side. The pivot must already be confirmed before it is taken. Independent of major BOS swing selection; no ATR filter.")
int inducementHistory = input.int(8, "Recent inducement marks", minval = 1, maxval = 20, group = G_I, tooltip = "? = taken level awaiting a reclaim. X = confirmed reclaim within a valid selected parent. Marks trace the earlier level/take interval; hover for confirmation and first-display times.")
type Origin
int start = na
int endTime = na
float rawTop = na
float rawBottom = na
float bodyTop = na
float bodyBottom = na
float top = na
float bottom = na
bool upperDone = false
bool lowerDone = false
float score = na
int liquidityTime = na
float liquidityPrice = na
bool reclaimed = false
bool imbalance = false
float departure = na
float efficiency = na
int direction = 0
int launchTime = na
int launchIndex = na
int formed = na
float sourceATR = na
float target = na
int targetTime = na
bool liquidityValid = false
bool retested = false
int firstTouch = na
bool inside = false
int known = na
int knownAt = na
int lastTouch = na
int selectedLeg = na
type Structure
int bias = 0
float upper = na
int upperTime = na
float lower = na
int lowerTime = na
float extreme = na
int extremeTime = na
float pullback = na
int pullbackTime = na
int legStart = na
float seedHigh = na
int seedHighTime = na
float seedLow = na
int seedLowTime = na
int eventDir = 0
float eventPrice = na
int eventTime = na
bool shift = false
type Frame
int stamp = na
int finish = na
int number = na
float hi = na
float lo = na
float cl = na
int breakDir = 0
float breakPrice = na
int breakTime = na
bool shift = false
int trend = 0
float upper = na
int upperTime = na
float lower = na
int lowerTime = na
int deliveryTime = na
float deliveryPrice = na
float returnPH = na
float returnPL = na
int returnPivotTime = na
int returnPivotNumber = na
Origin bullRecent = na
Origin bearRecent = na
Origin bullRoot = na
Origin bearRoot = na
type Evidence
int finish = na
float hi = na
float lo = na
bool tookHigh = false
bool tookLow = false
float highReference = na
float lowReference = na
type LiquidityMark
int direction = 0
int stamp = na
float level = na
float extreme = na
type Zone
Origin source = na
int confirmed = na
int available = na
int number = na
bool active = true
bool tested = false
int ended = na
array<box> areas = na
array<line> mids = na
line confirmation = na
label caption = na
line leader = na
type ReturnSwing
float level = na
int stamp = na
int number = na
int direction = 0
type Sweep
int id = na
Origin parent = na
float level = na
int referenceTime = na
int sweepTime = na
int sweepFinish = na
int confirmed = na
int status = 0
string reason = "Awaiting a strict close back through the taken level."
int firstShown = na
int confirmedShown = na
line stroke = na
label tag = na
type BOSMark
int stamp = na
int finish = na
int referenceTime = na
float level = na
int direction = 0
string proof = ""
int inducementID = na
int inducementStatus = na
string inducementProof = ""
line stroke = na
label tag = na
f_tfName(string tf) =>
float seconds = timeframe.in_seconds(tf)
seconds == 86400 ? "1D" : seconds >= 3600 ? str.tostring(int(seconds / 3600)) + "H" : str.tostring(int(seconds / 60)) + "m"
// Pure price/structure step. Inputs are already closed native-TF observations.
// The function has no ATR, source, score, displacement or inducement inputs.
f_structure(Structure previous, float ph, float pl, int pivotTime, float recentHigh, int recentHighTime, float recentLow, int recentLowTime, float hi, float lo, float cl, int stamp) =>
Structure s = previous.copy()
s.eventDir := 0
s.eventPrice := na
s.eventTime := na
s.shift := false
if s.bias == 0
if not na(ph) and (na(s.upper) or ph > s.upper)
s.upper := ph
s.upperTime := pivotTime
s.seedLow := recentLow
s.seedLowTime := recentLowTime
if not na(pl) and (na(s.lower) or pl < s.lower)
s.lower := pl
s.lowerTime := pivotTime
s.seedHigh := recentHigh
s.seedHighTime := recentHighTime
if not na(s.upper) and (na(s.seedLow) or lo < s.seedLow)
s.seedLow := lo
s.seedLowTime := stamp
if not na(s.lower) and (na(s.seedHigh) or hi > s.seedHigh)
s.seedHigh := hi
s.seedHighTime := stamp
if not na(s.upper) and not na(s.lower)
if cl > s.upper
s.eventDir := 1
s.eventPrice := s.upper
s.eventTime := s.upperTime
s.lower := s.seedLow
s.lowerTime := s.seedLowTime
else if cl < s.lower
s.eventDir := -1
s.eventPrice := s.lower
s.eventTime := s.lowerTime
s.upper := s.seedHigh
s.upperTime := s.seedHighTime
else if s.bias == 1
if hi > s.extreme
s.extreme := hi
s.extremeTime := stamp
// Only the external high of this leg becomes a continuation reference.
if na(s.upper) and not na(ph) and pivotTime >= s.legStart and ph >= s.extreme
s.upper := ph
s.upperTime := pivotTime
s.pullback := recentLow
s.pullbackTime := recentLowTime
if not na(s.upper) and (na(s.pullback) or lo < s.pullback)
s.pullback := lo
s.pullbackTime := stamp
if cl < s.lower
s.eventDir := -1
s.eventPrice := s.lower
s.eventTime := s.lowerTime
s.upper := s.extreme
s.upperTime := s.extremeTime
else if not na(s.upper) and cl > s.upper
s.eventDir := 1
s.eventPrice := s.upper
s.eventTime := s.upperTime
s.lower := s.pullback
s.lowerTime := s.pullbackTime
else
if lo < s.extreme
s.extreme := lo
s.extremeTime := stamp
if na(s.lower) and not na(pl) and pivotTime >= s.legStart and pl <= s.extreme
s.lower := pl
s.lowerTime := pivotTime
s.pullback := recentHigh
s.pullbackTime := recentHighTime
if not na(s.lower) and (na(s.pullback) or hi > s.pullback)
s.pullback := hi
s.pullbackTime := stamp
if cl > s.upper
s.eventDir := 1
s.eventPrice := s.upper
s.eventTime := s.upperTime
s.lower := s.extreme
s.lowerTime := s.extremeTime
else if not na(s.lower) and cl < s.lower
s.eventDir := -1
s.eventPrice := s.lower
s.eventTime := s.lowerTime
s.upper := s.pullback
s.upperTime := s.pullbackTime
if s.eventDir != 0
s.shift := s.bias != 0 and s.eventDir != s.bias
s.bias := s.eventDir
s.legStart := stamp
s.extreme := s.bias == 1 ? hi : lo
s.extremeTime := stamp
s.pullback := na
s.pullbackTime := na
if s.bias == 1
s.upper := na
s.upperTime := na
else
s.lower := na
s.lowerTime := na
s
// Raw wick/body geometry is immutable. Only consumption flags advance.
f_wicks(Origin original, float hi, float lo, int stamp) =>
Origin s = original.copy()
if not na(s.start) and stamp >= s.endTime
bool hasUpper = s.rawTop > s.bodyTop
bool hasLower = s.rawBottom < s.bodyBottom
bool upperHit = wickRule == "Reach wick tip" ? hi >= s.rawTop and lo <= s.rawTop : hi > s.bodyTop and lo < s.rawTop
bool lowerHit = wickRule == "Reach wick tip" ? lo <= s.rawBottom and hi >= s.rawBottom : lo < s.bodyBottom and hi > s.rawBottom
s.upperDone := s.upperDone or (hasUpper and upperHit)
s.lowerDone := s.lowerDone or (hasLower and lowerHit)
s.top := s.upperDone ? s.bodyTop : s.rawTop
s.bottom := s.lowerDone ? s.bodyBottom : s.rawBottom
s
f_departure(int direction, float atrNow, int lowTakeIndex, float lowTakeLevel, float lowTakePrice, int highTakeIndex, float highTakeLevel, float highTakePrice, bool preferExtreme) =>
Origin best = Origin.new()
float bestRank = -1e20
if not na(atrNow)
for offset = 1 to sourceScan
if na(time[offset]) or na(atrNow[offset])
break
float sourceATR = atrNow[offset]
bool opposite = direction == 1 ? close[offset] <= open[offset] : close[offset] >= open[offset]
bool smallBase = math.abs(close[offset] - open[offset]) <= sourceATR * 0.22
if opposite or smallBase
float top = high[offset]
float bottom = low[offset]
float bodyTop = math.max(open[offset], close[offset])
float bodyBottom = math.min(open[offset], close[offset])
int oldest = offset
// Consecutive, overlapping base candles only; never a broad range.
if baseBars > 1
for extra = 1 to baseBars - 1
int k = offset + extra
bool previousBase = direction == 1 ? close[k] <= open[k] : close[k] >= open[k]
previousBase := previousBase or math.abs(close[k] - open[k]) <= sourceATR * 0.22
bool overlaps = low[k] <= top and high[k] >= bottom
float nextTop = math.max(top, high[k])
float nextBottom = math.min(bottom, low[k])
if na(time[k]) or not previousBase or not overlaps or nextTop - nextBottom > sourceATR * maximumWidth
break
top := nextTop
bottom := nextBottom
bodyTop := math.max(bodyTop, math.max(open[k], close[k]))
bodyBottom := math.min(bodyBottom, math.min(open[k], close[k]))
oldest := k
float width = top - bottom
float departure = direction == 1 ? close - top : bottom - close
bool geometry = width >= syminfo.mintick * 2 and width <= sourceATR * maximumWidth and departure >= sourceATR * minimumDeparture
if geometry
int takeIndex = direction == 1 ? lowTakeIndex[offset - 1] : highTakeIndex[offset - 1]
float takeLevel = direction == 1 ? lowTakeLevel[offset - 1] : highTakeLevel[offset - 1]
float takePrice = direction == 1 ? lowTakePrice[offset - 1] : highTakePrice[offset - 1]
int oldestIndex = bar_index - oldest
bool liquidity = not na(takeIndex) and takeIndex >= oldestIndex - liquidityWindow and takeIndex <= bar_index - offset + 1
float originExtreme = direction == 1 ? bottom : top
liquidity := liquidity and math.abs(originExtreme - takePrice) <= sourceATR * 0.8
bool reclaimed = direction == 1 ? close > takeLevel : close < takeLevel
liquidity := liquidity and (liquidityMode == "Internal take" or reclaimed)
bool violated = false
bool departed = false
bool recycled = false
bool imbalance = false
int firstLeave = na
int firstLeaveOffset = na
int firstTouch = na
float largestBody = 0.0
float path = 0.0
// Walk in chronological order from base to detected departure.
for step = 0 to offset - 1
int k = offset - 1 - step
bool outsideDistal = direction == 1 ? close[k] < bottom - syminfo.mintick * 0.5 : close[k] > top + syminfo.mintick * 0.5
violated := violated or outsideDistal
bool overlaps = high[k] >= bottom and low[k] <= top
if departed and overlaps
recycled := true
if na(firstTouch)
firstTouch := time_close[k]
bool leaves = direction == 1 ? close[k] > top + sourceATR * 0.15 : close[k] < bottom - sourceATR * 0.15
if leaves and na(firstLeave)
firstLeave := time_close[k]
firstLeaveOffset := k
departed := departed or leaves
float directedBody = (close[k] - open[k]) * direction
largestBody := math.max(largestBody, directedBody)
path += math.abs(close[k] - close[k + 1])
// All three FVG candles must belong to this episode.
if k + 2 <= oldest
bool gap = direction == 1 ? low[k] > high[k + 2] : high[k] < low[k + 2]
imbalance := imbalance or gap
float net = (close - close[offset]) * direction
float efficiency = path > 0 ? net / path : 0.0
bool eligible = not violated and largestBody >= sourceATR * minimumBody and efficiency >= minimumEfficiency
if eligible
float score = 50.0 + 10.0 * math.min(departure / sourceATR / 3.0, 1.0) + 15.0 * math.min(efficiency, 1.0) + (reclaimed ? 10.0 : 0.0) + (imbalance ? 10.0 : 0.0)
score := math.min(score, 100.0)
// Prefer the actual launch extreme, not the latest high-scoring pause.
float rank = preferExtreme ? (direction == 1 ? -bottom : top) : -float(offset)
if rank > bestRank
int takeOffset = bar_index - takeIndex
Origin candidate = Origin.new(start = time[oldest], endTime = time_close[offset], rawTop = top, rawBottom = bottom, bodyTop = bodyTop, bodyBottom = bodyBottom, top = top, bottom = bottom, score = score, liquidityTime = liquidity ? time[takeOffset] : na, liquidityPrice = takeLevel, reclaimed = reclaimed, imbalance = imbalance, departure = departure / sourceATR, efficiency = efficiency, direction = direction, launchTime = firstLeave, launchIndex = bar_index - firstLeaveOffset, formed = time_close, sourceATR = sourceATR, liquidityValid = liquidity, retested = recycled, firstTouch = firstTouch, inside = high >= bottom and low <= top)
for step = 0 to offset - 1
int k = offset - 1 - step
candidate := f_wicks(candidate, high[k], low[k], time[k])
bool invalid = candidate.direction == 1 ? close[k] < candidate.bottom : close[k] > candidate.top
if invalid or candidate.top <= candidate.bottom
candidate := Origin.new()
break
if not na(candidate.start)
bestRank := rank
best := candidate
best
f_engine() =>
float ph = ta.pivothigh(high, swingLength, swingLength)
float pl = ta.pivotlow(low, swingLength, swingLength)
float recentHigh = high
float recentLow = low
int recentHighTime = time
int recentLowTime = time
if swingLength > 1
for k = 1 to swingLength - 1
if high[k] > recentHigh
recentHigh := high[k]
recentHighTime := time[k]
if low[k] < recentLow
recentLow := low[k]
recentLowTime := time[k]
var Structure state = Structure.new()
state := f_structure(state, ph, pl, time[swingLength], recentHigh, recentHighTime, recentLow, recentLowTime, high, low, close, time)
float atr = ta.atr(14)
float rangeLow = ta.lowest(low[1], liquidityLength)
float rangeHigh = ta.highest(high[1], liquidityLength)
var int lowTakeIndex = na
var int highTakeIndex = na
var float lowTakeLevel = na
var float highTakeLevel = na
var float lowTakePrice = na
var float highTakePrice = na
if low < rangeLow
lowTakeIndex := bar_index
lowTakeLevel := rangeLow
lowTakePrice := low
if high > rangeHigh
highTakeIndex := bar_index
highTakeLevel := rangeHigh
highTakePrice := high
// Capture both the recent base and the outer departure source. These are
// hidden candidates, not zones to plot merely because they formed.
Origin bullRecent = f_departure(1, atr, lowTakeIndex, lowTakeLevel, lowTakePrice, highTakeIndex, highTakeLevel, highTakePrice, false)
Origin bearRecent = f_departure(-1, atr, lowTakeIndex, lowTakeLevel, lowTakePrice, highTakeIndex, highTakeLevel, highTakePrice, false)
Origin bullRoot = f_departure(1, atr, lowTakeIndex, lowTakeLevel, lowTakePrice, highTakeIndex, highTakeLevel, highTakePrice, true)
Origin bearRoot = f_departure(-1, atr, lowTakeIndex, lowTakeLevel, lowTakePrice, highTakeIndex, highTakeLevel, highTakePrice, true)
// f_structure has just promoted the actual opposite swing of this BOS leg.
// This is a price/time swing, independent of any order-block geometry.
int deliveryTime = state.eventDir == 1 ? state.lowerTime : state.eventDir == -1 ? state.upperTime : na
float deliveryPrice = state.eventDir == 1 ? state.lower : state.eventDir == -1 ? state.upper : na
// Only native timeframe pivots are sent to the return-liquidity layer.
// The chart layer consumes prior confirmed swings before adding these.
float returnPH = ta.pivothigh(high, inducementWidth, inducementWidth)
float returnPL = ta.pivotlow(low, inducementWidth, inducementWidth)
Frame.new(stamp = time, finish = time_close, number = bar_index, hi = high, lo = low, cl = close, breakDir = state.eventDir, breakPrice = state.eventPrice, breakTime = state.eventTime, shift = state.shift, trend = state.bias, upper = state.upper, upperTime = state.upperTime, lower = state.lower, lowerTime = state.lowerTime, deliveryTime = deliveryTime, deliveryPrice = deliveryPrice, returnPH = returnPH, returnPL = returnPL, returnPivotTime = time[inducementWidth], returnPivotNumber = bar_index - inducementWidth, bullRecent = bullRecent.copy(), bearRecent = bearRecent.copy(), bullRoot = bullRoot.copy(), bearRoot = bearRoot.copy())
f_closedEngine() =>
Frame packet = f_engine()
packet[1]
// Evidence only: preserve internal-take logic without the execution model.
f_evidence() =>
float ph = ta.pivothigh(high, 2, 2)
float pl = ta.pivotlow(low, 2, 2)
float rangeHi = ta.highest(high[1], liquidityLength)
float rangeLo = ta.lowest(low[1], liquidityLength)
var float internalHi = na
var float internalLo = na
float hiRef = not na(internalHi) and high > internalHi ? internalHi : rangeHi
float loRef = not na(internalLo) and low < internalLo ? internalLo : rangeLo
bool tookHigh = not na(hiRef) and high > hiRef
bool tookLow = not na(loRef) and low < loRef
if not na(ph)
internalHi := ph
if not na(pl)
internalLo := pl
Evidence.new(finish = time_close, hi = high, lo = low, tookHigh = tookHigh, tookLow = tookLow, highReference = hiRef, lowReference = loRef)
f_closedEvidence() =>
Evidence packet = f_evidence()
packet[1]
f_recordEvidence(array<LiquidityMark> marks, Evidence e) =>
if e.tookHigh
array.push(marks, LiquidityMark.new(direction = -1, stamp = e.finish, level = e.highReference, extreme = e.hi))
if e.tookLow
array.push(marks, LiquidityMark.new(direction = 1, stamp = e.finish, level = e.lowReference, extreme = e.lo))
while array.size(marks) > 2200
array.shift(marks)
f_parentEvidence(Origin original, array<LiquidityMark> marks, float confirmedClose) =>
Origin source = original.copy()
if not na(source.start) and not source.liquidityValid and array.size(marks) > 0
int k = array.size(marks) - 1
while k >= 0
LiquidityMark mark = array.get(marks, k)
if mark.stamp < source.start
break
if mark.direction == source.direction and mark.stamp <= source.launchTime
bool atOrigin = mark.extreme >= source.rawBottom - source.sourceATR * 0.15 and mark.extreme <= source.rawTop + source.sourceATR * 0.15
bool reclaimed = (confirmedClose - mark.level) * source.direction > 0
if atOrigin and (liquidityMode == "Internal take" or reclaimed)
source.liquidityValid := true
source.liquidityTime := mark.stamp
source.liquidityPrice := mark.level
source.reclaimed := reclaimed
source.score := math.min(source.score + 10.0, 100.0)
break
k -= 1
source
// Update every hidden source on the same closed hourly observations as drawings.
// This is independent of the visible-zone archive and never resets on BOS.
f_cacheUpdate(array<Origin> memory, Frame f) =>
int k = array.size(memory) - 1
while k >= 0
Origin before = array.get(memory, k)
Origin after = f_wicks(before, f.hi, f.lo, f.stamp)
bool invalid = after.direction == 1 ? f.cl < after.bottom : f.cl > after.top
bool expired = f.number - after.launchIndex > zoneLifetime
if invalid or expired or after.top <= after.bottom
array.remove(memory, k)
else
bool touch = f.hi >= before.bottom and f.lo <= before.top
if f.finish > after.known and touch
after.lastTouch := f.stamp
after.retested := true
array.set(memory, k, after)
k -= 1
f_cacheAdd(array<Origin> memory, Origin original, Frame f, int available) =>
Origin s = original.copy()
bool accepted = not na(s.start) and s.liquidityValid and s.score >= minimumScore and s.top > s.bottom
if accepted
accepted := f.number - s.launchIndex <= zoneLifetime
if accepted
// Existing left parents own overlapping later refinements. Raw ranges
// preserve that ownership after one or both of the parent's wicks trim.
for prior in memory
if prior.direction == s.direction
float overlap = math.max(0.0, math.min(prior.rawTop, s.rawTop) - math.max(prior.rawBottom, s.rawBottom))
float fraction = overlap / math.max(syminfo.mintick, math.min(prior.rawTop - prior.rawBottom, s.rawTop - s.rawBottom))
if prior.start == s.start or fraction >= 0.65
accepted := false
if accepted
s.known := f.finish
s.knownAt := available
s.lastTouch := na
array.push(memory, s)
while array.size(memory) > memoryCapacity
array.shift(memory)
accepted
// "To the left" means qualified before the swing that launched this BOS leg.
// A newly detected base in that same leg is ineligible even if its score is high.
f_pickContext(array<Origin> memory, Frame f) =>
Origin chosen = Origin.new()
bool chosenResponded = false
if f.breakDir != 0 and not na(f.deliveryTime) and not na(f.deliveryPrice)
for s in memory
bool sameSide = s.direction == f.breakDir
bool preexisting = not na(s.known) and s.known <= f.deliveryTime and s.endTime <= f.deliveryTime and s.launchTime <= f.deliveryTime
bool outside = s.direction == -1 ? f.cl < s.bottom : f.cl > s.top
bool originInside = f.deliveryPrice >= s.rawBottom and f.deliveryPrice <= s.rawTop
bool touchedInLeg = not na(s.lastTouch) and s.lastTouch >= f.deliveryTime and s.lastTouch <= f.stamp
bool responded = originInside or touchedInLeg
bool aheadOfOrigin = s.direction == -1 ? s.rawTop >= f.deliveryPrice : s.rawBottom <= f.deliveryPrice
bool valid = s.liquidityValid and s.score >= minimumScore and s.top > s.bottom
if sameSide and preexisting and outside and valid and (responded or aheadOfOrigin)
bool betterRelationship = responded and not chosenResponded
bool newer = s.endTime > chosen.endTime or (s.endTime == chosen.endTime and s.start > chosen.start)
if na(chosen.start) or betterRelationship or (responded == chosenResponded and newer)
chosen := s.copy()
chosenResponded := responded
if not na(chosen.start)
chosen.target := f.breakPrice
chosen.targetTime := f.breakTime
chosen.selectedLeg := f.deliveryTime
chosen
f_color(Zone z) =>
z.source.direction == 1 ? demandColor : supplyColor
f_caption(Origin s) =>
f_tfName(contextTF) + (s.direction == 1 ? " +OB | left context" : " -OB | left context")
f_proof(Zone z) =>
Origin s = z.source
string proof = f_caption(s)
proof += "\nSource: " + str.format_time(s.start, "MMM d HH:mm", syminfo.timezone)
proof += "\nSource qualified: " + str.format_time(s.known, "MMM d HH:mm", syminfo.timezone)
proof += "\nFirst observed: " + str.format_time(s.knownAt, "MMM d HH:mm", syminfo.timezone)
proof += "\nBreaking leg began: " + str.format_time(s.selectedLeg, "MMM d HH:mm", syminfo.timezone)
proof += "\nSelected/displayed: " + str.format_time(z.available, "MMM d HH:mm", syminfo.timezone)
proof += "\nRaw high / low: " + str.tostring(s.rawTop, format.mintick) + " / " + str.tostring(s.rawBottom, format.mintick)
proof += "\nBody high / low: " + str.tostring(s.bodyTop, format.mintick) + " / " + str.tostring(s.bodyBottom, format.mintick)
proof += "\nUpper wick consumed: " + (s.upperDone ? "yes" : "no") + " | lower: " + (s.lowerDone ? "yes" : "no")
proof += "\nInducement: " + str.format_time(s.liquidityTime, "MMM d HH:mm", syminfo.timezone)
proof += "\nOB score: " + str.tostring(s.score, "#") + "/100, not probability"
proof += "\nBOS uses structural wick levels, independently of OB boundaries."
proof += "\nInitial source tracing is retrospective. Subsequent trims start when observed."
proof
f_segment(Zone z, int left, int right) =>
Origin s = z.source
color col = f_color(z)
box area = box.new(left = left, top = s.top, right = right, bottom = s.bottom, xloc = xloc.bar_time, bgcolor = color.new(col, fillTransparency), border_color = color.new(col, 25), border_width = 1)
array.push(z.areas, area)
if showMidpoint
float mid = (s.top + s.bottom) / 2
line middle = line.new(x1 = left, y1 = mid, x2 = right, y2 = mid, xloc = xloc.bar_time, color = color.new(col, 40), style = line.style_dotted)
array.push(z.mids, middle)
f_closeSegment(Zone z, int atTime) =>
if array.size(z.areas) > 0
box.set_right(array.get(z.areas, array.size(z.areas) - 1), atTime)
if array.size(z.mids) > 0
line.set_x2(array.get(z.mids, array.size(z.mids) - 1), atTime)
f_delete(Zone z) =>
for b in z.areas
box.delete(b)
for m in z.mids
line.delete(m)
line.delete(z.confirmation)
label.delete(z.caption)
line.delete(z.leader)
f_finish(Zone z, int atTime) =>
z.active := false
z.ended := atTime
f_closeSegment(z, atTime)
if array.size(z.areas) > 0
box last = array.get(z.areas, array.size(z.areas) - 1)
box.set_bgcolor(last, color.new(f_color(z), 94))
box.set_border_style(last, line.style_dotted)
label.delete(z.caption)
line.delete(z.leader)
z.caption := na
z.leader := na
f_prune(array<Zone> zones) =>
for side = 0 to 1
int direction = side == 0 ? -1 : 1
int count = 0
int weakest = -1
float score = 1e20
if array.size(zones) > 0
for k = 0 to array.size(zones) - 1
Zone z = array.get(zones, k)
if z.active and z.source.direction == direction
count += 1
if z.available < score
score := z.available
weakest := k
if count > perSide and weakest >= 0
Zone removed = array.remove(zones, weakest)
f_delete(removed)
int archived = 0
for z in zones
if not z.active
archived += 1
while archived > archiveCount
int oldest = -1
int ended = na
for k = 0 to array.size(zones) - 1
Zone z = array.get(zones, k)
if not z.active and (na(ended) or z.ended < ended)
oldest := k
ended := z.ended
if oldest < 0
break
Zone removed = array.remove(zones, oldest)
f_delete(removed)
archived -= 1
f_update(array<Zone> zones, Frame f, int available) =>
bool refined = false
for z in zones
if z.active and f.finish > z.confirmed
Origin before = z.source
Origin after = f_wicks(before, f.hi, f.lo, f.stamp)
bool changed = after.top != before.top or after.bottom != before.bottom
bool touched = f.hi >= before.bottom and f.lo <= before.top
z.tested := z.tested or touched
z.source := after
bool invalid = after.direction == 1 ? f.cl < after.bottom : f.cl > after.top
bool empty = after.top <= after.bottom
bool expired = f.number - z.number > zoneLifetime
if invalid or empty or expired
f_finish(z, available)
else if changed
// Do not rewrite the old box's historical top or bottom.
f_closeSegment(z, available)
f_segment(z, available, available)
label.set_text(z.caption, f_caption(after))
label.set_tooltip(z.caption, f_proof(z))
refined := true
refined
f_add(array<Zone> zones, Origin original, Frame f, int available) =>
Origin s = original.copy()
bool accepted = not na(s.start) and s.liquidityValid and s.score >= minimumScore and s.top > s.bottom
if accepted
for z in zones
if z.source.direction == s.direction
bool sameSource = z.source.start == s.start
float overlap = math.max(0.0, math.min(s.top, z.source.top) - math.max(s.bottom, z.source.bottom))
float fraction = overlap / math.max(syminfo.mintick, math.min(s.top - s.bottom, z.source.top - z.source.bottom))
if sameSource or (z.active and fraction >= 0.65)
accepted := false
if accepted
Zone z = Zone.new(source = s, confirmed = f.finish, available = available, number = s.launchIndex, tested = s.retested, areas = array.new<box>(), mids = array.new<line>())
int left = traceOrigin ? s.start : available
f_segment(z, left, available)
color col = f_color(z)
float mid = (s.top + s.bottom) / 2
if markConfirmation
z.confirmation := line.new(x1 = available, y1 = s.bottom, x2 = available, y2 = s.top, xloc = xloc.bar_time, color = color.new(col, 15), style = line.style_dotted)
z.caption := label.new(x = available, y = mid, text = f_caption(s), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(col, 100), textcolor = chart.fg_color, size = size.small, tooltip = f_proof(z))
z.leader := line.new(x1 = available, y1 = mid, x2 = available, y2 = mid, xloc = xloc.bar_time, color = color.new(col, 45))
array.push(zones, z)
f_prune(zones)
accepted := false
for kept in zones
if kept.source.start == s.start and kept.source.direction == s.direction
accepted := true
accepted
// The new layer never feeds a reclassified event back into f_structure,
// f_departure, f_pickContext or f_add. Approved v4 OB positions stay intact.
f_returnReference(Origin s, float level, int referenceTime, Frame f) =>
bool known = not na(s.known) and s.known <= f.stamp
bool later = not na(referenceTime) and referenceTime > s.launchTime and referenceTime >= s.endTime and referenceTime < f.stamp
bool inside = not na(level) and level >= s.bottom and level <= s.top
bool touching = f.hi >= s.bottom and f.lo <= s.top
known and later and inside and touching and s.liquidityValid
// status: 0 pending, 1 reclaimed, -1 invalidated, -2 expired.
// Confirmation describes the reclaim only, not a profitable future outcome.
f_sweepStep(Sweep previous, Frame f) =>
Sweep e = previous.copy()
if not na(e.parent) and e.status == 0
Origin s = f_wicks(e.parent, f.hi, f.lo, f.stamp)
e.parent := s
bool invalid = s.direction == -1 ? f.cl > s.top : f.cl < s.bottom
bool expired = f.number - s.launchIndex > zoneLifetime
bool reclaim = s.direction == -1 ? f.cl < e.level : f.cl > e.level
// Apply parent invalidation and wick refinement BEFORE any reclaim.
if invalid or s.top <= s.bottom
e.status := -1
e.reason := "Parent OB invalidated before reclaim. This is not confirmed inducement."
else if expired
e.status := -2
e.reason := "Parent OB expired before reclaim. This is not confirmed inducement."
else if reclaim
e.status := 1
e.confirmed := f.finish
e.reason := "Strict native close reclaimed the taken level while the parent remained valid."
e
// Keep all still-untaken native pivots. Filtering and ranking happen within
// each parent's own post-launch history, never against the original OB high.
f_internalReference(array<ReturnSwing> swings, Origin s, Frame f) =>
ReturnSwing best = ReturnSwing.new()
for pivot in swings
if pivot.direction == s.direction and f_returnReference(s, pivot.level, pivot.stamp, f)
bool moreExtreme = na(best.level) or (s.direction == -1 ? pivot.level > best.level : pivot.level < best.level)
if moreExtreme
best := pivot
best
f_sweepCandidate(Origin s, Frame f, ReturnSwing pivot) =>
Sweep e = Sweep.new()
// BOS does not substitute its own level for the highest internal swing.
// When BOS takes that same swing, the existing label is still reclassified.
bool taken = s.direction == -1 ? f.hi > pivot.level : f.lo < pivot.level
if f_returnReference(s, pivot.level, pivot.stamp, f) and taken
e := Sweep.new(parent = s.copy(), level = pivot.level, referenceTime = pivot.stamp, sweepTime = f.stamp, sweepFinish = f.finish)
e := f_sweepStep(e, f)
if e.status < 0
e := Sweep.new()
e
f_captureSweeps(array<Sweep> events, array<Origin> memory, array<ReturnSwing> swings, Frame f, int serial) =>
int next = serial
for s in memory
// Avoid scanning liquidity for sources nowhere near this candle.
if s.known <= f.stamp and f.hi >= s.bottom and f.lo <= s.top
ReturnSwing pivot = f_internalReference(swings, s, f)
Sweep candidate = f_sweepCandidate(s, f, pivot)
if not na(candidate.parent)
bool duplicate = false
for prior in events
if prior.parent.start == s.start and prior.parent.direction == s.direction and prior.referenceTime == candidate.referenceTime
duplicate := true
break
if not duplicate
next += 1
candidate.id := next
array.push(events, candidate)
while array.size(events) > 320
Sweep removed = array.shift(events)
line.delete(removed.stroke)
label.delete(removed.tag)
next
f_updateReturnSwings(array<ReturnSwing> swings, Frame f) =>
// Called AFTER every parent has checked the previously known pivots.
// Taking a smaller pivot consumes it but does not qualify an X when a
// higher internal high (or lower internal low) is still waiting.
int k = array.size(swings) - 1
while k >= 0
ReturnSwing pivot = array.get(swings, k)
bool taken = pivot.direction == -1 ? f.hi > pivot.level : f.lo < pivot.level
if taken or f.number - pivot.number > zoneLifetime
array.remove(swings, k)
k -= 1
if not na(f.returnPH)
array.push(swings, ReturnSwing.new(level = f.returnPH, stamp = f.returnPivotTime, number = f.returnPivotNumber, direction = -1))
if not na(f.returnPL)
array.push(swings, ReturnSwing.new(level = f.returnPL, stamp = f.returnPivotTime, number = f.returnPivotNumber, direction = 1))
while array.size(swings) > 2000
array.shift(swings)
f_sweepBOS(Sweep e, BOSMark b) =>
bool sameLevel = e.referenceTime == b.referenceTime and e.level == b.level
bool sameSide = b.direction == -e.parent.direction
bool during = b.stamp >= e.sweepTime and (na(e.confirmed) or b.finish <= e.confirmed)
sameLevel and sameSide and during
f_selectedParent(Sweep e, array<Zone> zones) =>
bool selected = false
for z in zones
if z.source.start == e.parent.start and z.source.direction == e.parent.direction
if z.active or e.sweepFinish <= z.ended
selected := true
break
selected
f_sweepProof(Sweep e) =>
string proofText = f_tfName(contextTF) + (e.parent.direction == -1 ? " supply: high taken" : " demand: low taken")
proofText += "\nHighest/lowest unswept internal pivot after the parent departure."
proofText += "\nLevel: " + str.tostring(e.level, format.mintick)
proofText += "\nParent source: " + str.format_time(e.parent.start, "MMM d HH:mm", syminfo.timezone)
proofText += "\nTake closed: " + str.format_time(e.sweepFinish, "MMM d HH:mm", syminfo.timezone)
if not na(e.confirmed)
proofText += "\nReclaim confirmed: " + str.format_time(e.confirmed, "MMM d HH:mm", syminfo.timezone)
proofText += "\nFirst displayed: " + str.format_time(e.firstShown, "MMM d HH:mm", syminfo.timezone)
if not na(e.confirmedShown)
proofText += "\nConfirmed X first displayed: " + str.format_time(e.confirmedShown, "MMM d HH:mm", syminfo.timezone)
proofText += "\n" + e.reason
proofText += "\nThe mark traces earlier liquidity. No historical alert is backdated."
proofText
// Rendering only: chart prices never enter the hourly structure model.
// A clock-time midpoint can land inside a weekend. Use the middle actual
// chart bar instead, retaining timestamp anchoring when scrolling/zooming.
f_chartPosition(array<int> stamps, int target) =>
int left = 0
int right = array.size(stamps)
while left < right
int middle = int((left + right) / 2)
if array.get(stamps, middle) < target
left := middle + 1
else
right := middle
left
f_centerTime(array<int> stamps, int startTime, int endTime) =>
int centered = int((startTime + endTime) / 2)
int count = array.size(stamps)
if count > 0 and startTime >= array.get(stamps, 0)
int first = f_chartPosition(stamps, startTime)
int last = f_chartPosition(stamps, endTime)
int middle = math.min(count - 1, int((first + last) / 2))
centered := array.get(stamps, middle)
centered
f_drawSweep(Sweep e, array<int> stamps) =>
if na(e.stroke)
e.stroke := line.new(x1 = e.referenceTime, y1 = e.level, x2 = e.sweepFinish, y2 = e.level, xloc = xloc.bar_time, width = 1)
e.tag := label.new(x = e.sweepFinish, y = e.level, text = "", xloc = xloc.bar_time, style = label.style_none, size = size.small)
int atTime = f_centerTime(stamps, e.referenceTime, e.sweepFinish)
line.set_color(e.stroke, color.new(chart.fg_color, e.status == 1 ? 15 : 55))
line.set_style(e.stroke, e.status == 1 ? line.style_dotted : line.style_dashed)
label.set_xy(e.tag, atTime, e.level)
label.set_textalign(e.tag, text.align_center)
label.set_text(e.tag, e.status == 1 ? "×" : "?")
label.set_textcolor(e.tag, color.new(chart.fg_color, e.status == 1 ? 0 : 40))
label.set_tooltip(e.tag, f_sweepProof(e))
f_publishSweeps(array<Sweep> events, array<Zone> zones, array<BOSMark> bosMarks, array<int> stamps, Frame f, int available) =>
bool confirmedNow = false
for e in events
if na(e.firstShown) and e.status >= 0 and f_selectedParent(e, zones)
e.firstShown := available
if not na(e.firstShown) and e.status == 1 and na(e.confirmedShown)
e.confirmedShown := available
// A previously reclaimed event may be attached when its parent
// is selected later. Draw its history, but do not fire a new alert.
confirmedNow := confirmedNow or e.confirmed == f.finish
// Only retained parent boxes can display a mark. Limit all inducement
// drawings together, including ones replacing an ordinary BOS caption.
array<Sweep> rendered = array.new<Sweep>()
int r = array.size(events) - 1
while r >= 0 and array.size(rendered) < inducementHistory
Sweep e = array.get(events, r)
bool visible = not na(e.firstShown) and e.status >= 0 and f_selectedParent(e, zones)
if visible
for other in rendered
if other.referenceTime == e.referenceTime and other.parent.direction == e.parent.direction
visible := false
if visible
array.push(rendered, e)
r -= 1
// Keep an existing classification synchronized even when its event fails.
// A new binding must belong to a retained, visible parent. A hidden or old
// classified break is hidden, never relabeled as an ordinary BOS again.
for b in bosMarks
for e in events
if b.inducementID == e.id
b.inducementStatus := e.status
b.inducementProof := f_sweepProof(e)
break
if na(b.inducementID) or b.inducementStatus < 0
for e in rendered
if f_sweepBOS(e, b)
b.inducementID := e.id
b.inducementStatus := e.status
b.inducementProof := f_sweepProof(e)
break
bool contextual = not na(b.inducementStatus) and b.inducementStatus >= 0
bool visible = not contextual
for e in rendered
if b.inducementID == e.id
visible := true
color col = b.direction == 1 ? demandColor : supplyColor
string caption = contextual ? (b.inducementStatus == 1 ? "×" : "?") : f_tfName(contextTF) + " BOS"
line.set_color(b.stroke, not visible ? color.new(col, 100) : contextual ? color.new(chart.fg_color, b.inducementStatus == 1 ? 15 : 55) : col)
line.set_style(b.stroke, contextual ? (b.inducementStatus == 1 ? line.style_dotted : line.style_dashed) : line.style_solid)
label.set_xy(b.tag, f_centerTime(stamps, b.referenceTime, b.finish), b.level)
label.set_textalign(b.tag, text.align_center)
label.set_text(b.tag, visible ? caption : "")
label.set_textcolor(b.tag, chart.fg_color)
label.set_tooltip(b.tag, contextual ? b.inducementProof : b.proof)
// The most recent visible events own their marks. A matching BOS already
// supplies the line/label, so never stack an X over an unchanged BOS label.
int k = array.size(events) - 1
while k >= 0
Sweep e = array.get(events, k)
bool visible = false
for other in rendered
if other.id == e.id
visible := true
bool attached = false
for b in bosMarks
if b.inducementID == e.id and b.inducementStatus >= 0
attached := true
if visible and not attached
f_drawSweep(e, stamps)
else
line.delete(e.stroke)
label.delete(e.tag)
e.stroke := na
e.tag := na
k -= 1
confirmedNow
float chartSeconds = timeframe.in_seconds()
float contextSeconds = timeframe.in_seconds(contextTF)
if barstate.isfirst
if not chart.is_standard or na(chartSeconds) or chartSeconds > contextSeconds
runtime.error("Use standard time-based candles at or below the structure timeframe. Defaults: 1H structure on a 1m, 3m, 5m, 15m or 1H chart.")
Frame packet = na
if chartSeconds == contextSeconds
packet := f_engine()
else
packet := request.security(syminfo.tickerid, contextTF, f_closedEngine(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
Evidence evidencePacket = na
array<Evidence> intrabars = array.new<Evidence>()
if useEvidence
if chartSeconds == 300
evidencePacket := f_evidence()
else if chartSeconds < 300
evidencePacket := request.security(syminfo.tickerid, "5", f_closedEvidence(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
else
intrabars := request.security_lower_tf(syminfo.tickerid, "5", f_evidence())
var array<Zone> zones = array.new<Zone>()
var array<Origin> sourceMemory = array.new<Origin>()
var array<LiquidityMark> marks = array.new<LiquidityMark>()
var array<BOSMark> bosMarks = array.new<BOSMark>()
var array<Sweep> sweeps = array.new<Sweep>()
var array<ReturnSwing> returnSwings = array.new<ReturnSwing>()
var array<int> chartStamps = array.new<int>()
var int sweepSerial = 0
var int seen = na
var int seenEvidence = na
var Frame latest = na
var line upperLine = na
var line lowerLine = na
var label upperLabel = na
var label lowerLabel = na
bool bullishBOS = false
bool bearishBOS = false
bool newOB = false
bool refinedOB = false
bool confirmedInducement = false
if barstate.isconfirmed
// Bounded timestamp book, trimmed in batches instead of shifting per bar.
// Used exclusively to center labels across missing sessions.
if array.size(chartStamps) >= 100000
chartStamps := array.copy(array.slice(chartStamps, 10000, array.size(chartStamps)))
array.push(chartStamps, time)
if useEvidence
if not na(evidencePacket) and not na(evidencePacket.finish) and (na(seenEvidence) or evidencePacket.finish > seenEvidence)
f_recordEvidence(marks, evidencePacket)
seenEvidence := evidencePacket.finish
for e in intrabars
if na(seenEvidence) or e.finish > seenEvidence
f_recordEvidence(marks, e)
seenEvidence := e.finish
if not na(packet) and not na(packet.finish) and (na(seen) or packet.finish > seen)
seen := packet.finish
latest := packet
if showInducement
if array.size(sweeps) > 0
for k = 0 to array.size(sweeps) - 1
Sweep e = array.get(sweeps, k)
if e.status == 0
array.set(sweeps, k, f_sweepStep(e, packet))
// Read the parent geometry known BEFORE this candle refines it.
// f_sweepCandidate still rejects an invalidating candle after trim.
sweepSerial := f_captureSweeps(sweeps, sourceMemory, returnSwings, packet, sweepSerial)
f_updateReturnSwings(returnSwings, packet)
refinedOB := f_update(zones, packet, time_close)
f_cacheUpdate(sourceMemory, packet)
Origin bullRoot = useEvidence ? f_parentEvidence(packet.bullRoot, marks, packet.cl) : packet.bullRoot.copy()
Origin bearRoot = useEvidence ? f_parentEvidence(packet.bearRoot, marks, packet.cl) : packet.bearRoot.copy()
Origin bullRecent = useEvidence ? f_parentEvidence(packet.bullRecent, marks, packet.cl) : packet.bullRecent.copy()
Origin bearRecent = useEvidence ? f_parentEvidence(packet.bearRecent, marks, packet.cl) : packet.bearRecent.copy()
f_cacheAdd(sourceMemory, bullRoot, packet, time_close)
f_cacheAdd(sourceMemory, bearRoot, packet, time_close)
f_cacheAdd(sourceMemory, bullRecent, packet, time_close)
f_cacheAdd(sourceMemory, bearRecent, packet, time_close)
bullishBOS := packet.breakDir == 1
bearishBOS := packet.breakDir == -1
// Raw BOS still drives the unchanged context selector. Only display and
// BOS alerts can be reclassified by the selected-parent overlay below.
if packet.breakDir != 0
color col = packet.breakDir == 1 ? demandColor : supplyColor
line bos = line.new(x1 = packet.breakTime, y1 = packet.breakPrice, x2 = packet.finish, y2 = packet.breakPrice, xloc = xloc.bar_time, color = col, width = 1)
int middle = f_centerTime(chartStamps, packet.breakTime, packet.finish)
string proof = "Strict " + f_tfName(contextTF) + " close beyond " + str.tostring(packet.breakPrice, format.mintick)
proof += "\nConfirmed: " + str.format_time(packet.finish, "MMM d HH:mm", syminfo.timezone)
proof += "\nFirst available: " + str.format_time(time_close, "MMM d HH:mm", syminfo.timezone)
proof += "\nNo ATR buffer. No qualifying OB is required."
label caption = label.new(x = middle, y = packet.breakPrice, text = f_tfName(contextTF) + " BOS", xloc = xloc.bar_time, style = label.style_none, textcolor = chart.fg_color, size = size.small, tooltip = proof)
array.push(bosMarks, BOSMark.new(stamp = packet.stamp, finish = packet.finish, referenceTime = packet.breakTime, level = packet.breakPrice, direction = packet.breakDir, proof = proof, stroke = bos, tag = caption))
while array.size(bosMarks) > bosHistory
BOSMark removed = array.shift(bosMarks)
line.delete(removed.stroke)
label.delete(removed.tag)
Origin source = f_pickContext(sourceMemory, packet)
newOB := f_add(zones, source, packet, time_close)
f_prune(zones)
if showInducement
confirmedInducement := f_publishSweeps(sweeps, zones, bosMarks, chartStamps, packet, time_close)
for b in bosMarks
if b.stamp == packet.stamp and not na(b.inducementStatus) and b.inducementStatus >= 0
bullishBOS := false
bearishBOS := false
if barstate.islast
int chartMS = int(chartSeconds * 1000)
int right = time_close + projectBars * chartMS
int labelTime = right + 2 * chartMS
array<int> visible = array.new<int>()
float highest = na
float lowest = na
if array.size(zones) > 0
for k = 0 to array.size(zones) - 1
Zone z = array.get(zones, k)
if z.active
f_closeSegment(z, right)
array.push(visible, k)
highest := na(highest) ? z.source.top : math.max(highest, z.source.top)
lowest := na(lowest) ? z.source.bottom : math.min(lowest, z.source.bottom)
if array.size(visible) > 1
for i = 1 to array.size(visible) - 1
int key = array.get(visible, i)
Zone keyZone = array.get(zones, key)
float keyMid = (keyZone.source.top + keyZone.source.bottom) / 2
int j = i - 1
while j >= 0
Zone other = array.get(zones, array.get(visible, j))
if (other.source.top + other.source.bottom) / 2 <= keyMid
break
array.set(visible, j + 1, array.get(visible, j))
j -= 1
array.set(visible, j + 1, key)
float gap = math.max(nz(highest - lowest) * 0.025, syminfo.mintick * 8)
float previousY = na
for index in visible
Zone z = array.get(zones, index)
float mid = (z.source.top + z.source.bottom) / 2
float y = na(previousY) ? mid : math.max(mid, previousY + gap)
label.set_xy(z.caption, labelTime, y)
line.set_xy1(z.leader, right, mid)
line.set_xy2(z.leader, labelTime, y)
previousY := y
line.delete(upperLine)
line.delete(lowerLine)
label.delete(upperLabel)
label.delete(lowerLabel)
if showLevels and not na(latest)
if not na(latest.upper)
upperLine := line.new(x1 = latest.upperTime, y1 = latest.upper, x2 = right, y2 = latest.upper, xloc = xloc.bar_time, color = supplyColor, style = line.style_dashed)
upperLabel := label.new(x = labelTime, y = latest.upper, text = latest.trend == -1 ? "Protected high" : "External high", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(supplyColor, 100), textcolor = chart.fg_color, size = size.small)
if not na(latest.lower)
lowerLine := line.new(x1 = latest.lowerTime, y1 = latest.lower, x2 = right, y2 = latest.lower, xloc = xloc.bar_time, color = demandColor, style = line.style_dashed)
lowerLabel := label.new(x = labelTime, y = latest.lower, text = latest.trend == 1 ? "Protected low" : "External low", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(demandColor, 100), textcolor = chart.fg_color, size = size.small)
alertcondition(bullishBOS, "Bullish HTF BOS", "Closed HTF candle above major structure, without a displayed parent inducement classification. {{ticker}}")
alertcondition(bearishBOS, "Bearish HTF BOS", "Closed HTF candle below major structure, without a displayed parent inducement classification. {{ticker}}")
alertcondition(newOB, "Selected HTF left context", "BOS selected a preexisting higher-timeframe parent zone to the left. {{ticker}}")
alertcondition(refinedOB, "HTF OB wick refined", "A closed source candle consumed an OB wick; remaining boundaries were refined. {{ticker}}")
alertcondition(confirmedInducement, "Confirmed HTF parent inducement", "A taken HTF swing was reclaimed while its selected parent OB remained valid. {{ticker}}")