本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0.
// https://mozilla.org/MPL/2.0/
// Copyright Keyvan Khodakhah. Original Swing v14.31 structural bodies retained below.
// Advanced structure implementation and compatibility extraction: 2026-10-17.
//@description ITBF structural engine: legacy-compatible S/R, TL, SMS and target services plus persistent native-MTF structure and regression. No main trading authority or network/webhook side effects.
library("ITBFStructureEngine", overlay=true, dynamic_requests=false)
// === SR COMPATIBILITY SERVICE ===
export type LegacySRConfig
float clusterDistanceMult
color colResBorder
color colResFill
color colRetestResBorder
color colRetestResFill
color colRetestSupBorder
color colRetestSupFill
color colSupBorder
color colSupFill
int minClusterPivots
int pivotLeft
int pivotRight
float srBreakBufferAtr
int srMaxStoredPivots
float srRetestTolMult
bool srRetestUseWick
bool v1429HTFCleanStructure
bool v1429HTFDaily
bool v1429HTFWeekly
float v1429MacroZoneDistanceAtr
float v1429MacroZoneDistancePct
int v1429RetestZoneBarsEff
int v1429SrLookbackEff
int v1429SrTouchGapEff
float v146SConfluenceTolAtr
bool v146SDemandActive
float v146SDemandBottom
float v146SDemandTop
bool v146SShowSignalZones
bool v146SSupplyActive
float v146SSupplyBottom
float v146SSupplyTop
export type LegacySRResult
bool allowBuy
bool allowSell
float clusterDistance
bool isNearResistance
bool isNearRetestResistance
bool isNearRetestSupport
bool isNearSupport
float pivotH
float pivotL
float resistance
float retestResistance
float retestSupport
bool srBreakDnEvent
float srBreakDnLevelNow
bool srBreakUpEvent
float srBreakUpLevelNow
int srResistanceSpan
int srResistanceTouches
bool srRetestBear
bool srRetestBull
int srSupportSpan
int srSupportTouches
float src
float support
compat_SR_f_best_major_zone(LegacySRConfig _cfg, array<float> vals, array<int> bars, float threshold, int minTouches, int minGapBars, bool wantResistance, float px, float atrNow) =>
float bestZone = na
float bestScore = -1.0e10
int bestHits = 0
int bestSpan = 0
int n = array.size(vals)
if n > 0 and threshold > 0 and atrNow > 0
for i = 0 to n - 1
float cur = array.get(vals, i)
bool sideOK = wantResistance ? cur >= px - threshold : cur <= px + threshold
if sideOK
int hits = 0
float sumV = 0.0
int newestB = na
int oldestB = na
int lastAcceptedB = na
for j = 0 to n - 1
float v = array.get(vals, j)
int b = array.get(bars, j)
if math.abs(v - cur) <= threshold and (na(lastAcceptedB) or math.abs(b - lastAcceptedB) >= minGapBars)
hits += 1
sumV += v
newestB := na(newestB) ? b : math.max(newestB, b)
oldestB := na(oldestB) ? b : math.min(oldestB, b)
lastAcceptedB := b
if hits >= minTouches
float zone = sumV / hits
int span = na(newestB) or na(oldestB) ? 0 : newestB - oldestB
int age = na(newestB) ? _cfg.v1429SrLookbackEff : bar_index - newestB
float distAtr = math.abs(zone - px) / math.max(atrNow, syminfo.mintick)
float score = hits * 100.0 + math.min(span, _cfg.v1429SrLookbackEff) * 0.20 - math.min(age, _cfg.v1429SrLookbackEff) * 0.04 - math.min(distAtr, 25.0) * 1.50
if score > bestScore
bestScore := score
bestZone := zone
bestHits := hits
bestSpan := span
[bestZone, bestHits, bestSpan]
compat_SR_f_time_back(_bars) =>
int b = _bars
int off = bar_index > b ? b : bar_index
time[off]
//@function v14.31 SR extraction. Call once per chart execution at original evaluation point.
export legacySR(LegacySRConfig _cfg) =>
// [A] ADVANCED S/R — ROLLING, RANKED MAJOR SUPPLY/DEMAND ZONES
// =============================================================================
// The S/R layer keeps the familiar box presentation while upgrading level selection:
// • pivots are truly limited to srLookbackBars (no unbounded historical arrays)
// • touches must be independently separated in time
// • competing clusters are ranked by touches + span + recency + price relevance
// • break/retest state is one-shot; it is not reset on every bar beyond the zone
clusterDistance = ta.atr(14) * _cfg.clusterDistanceMult
src = close
var float[] pivotHighs = array.new<float>()
var int[] pivotHighBars = array.new<int>()
var float[] pivotLows = array.new<float>()
var int[] pivotLowBars = array.new<int>()
pivotH = ta.pivothigh(high, _cfg.pivotLeft, _cfg.pivotRight)
pivotL = ta.pivotlow(low, _cfg.pivotLeft, _cfg.pivotRight)
if not na(pivotH)
array.unshift(pivotHighs, pivotH)
array.unshift(pivotHighBars, bar_index - _cfg.pivotRight)
if not na(pivotL)
array.unshift(pivotLows, pivotL)
array.unshift(pivotLowBars, bar_index - _cfg.pivotRight)
// Hard bounds protect performance on very long chart histories.
while array.size(pivotHighBars) > 0 and (bar_index - array.get(pivotHighBars, array.size(pivotHighBars) - 1) > _cfg.v1429SrLookbackEff or array.size(pivotHighBars) > _cfg.srMaxStoredPivots)
array.pop(pivotHighs)
array.pop(pivotHighBars)
while array.size(pivotLowBars) > 0 and (bar_index - array.get(pivotLowBars, array.size(pivotLowBars) - 1) > _cfg.v1429SrLookbackEff or array.size(pivotLowBars) > _cfg.srMaxStoredPivots)
array.pop(pivotLows)
array.pop(pivotLowBars)
// Select the strongest relevant cluster. High clusters prefer the resistance side
// of price; low clusters prefer the support side. The cluster center is the mean
// of its independently separated touches, not simply the newest pivot.
[rawResistance, srResistanceTouches, srResistanceSpan] = compat_SR_f_best_major_zone(_cfg, pivotHighs, pivotHighBars, clusterDistance, _cfg.minClusterPivots, _cfg.v1429SrTouchGapEff, true, close, ta.atr(14))
[rawSupport, srSupportTouches, srSupportSpan] = compat_SR_f_best_major_zone(_cfg, pivotLows, pivotLowBars, clusterDistance, _cfg.minClusterPivots, _cfg.v1429SrTouchGapEff, false, close, ta.atr(14))
resistance = rawResistance
support = rawSupport
// Stateful flip/retest trackers. A level is frozen only on the actual break bar.
var float retestResistance = na
var int retestResistanceExpiry = na
var bool retestResistanceConsumed = false
var float retestSupport = na
var int retestSupportExpiry = na
var bool retestSupportConsumed = false
float srBreakBuffer = ta.atr(14) * _cfg.srBreakBufferAtr
float _resPrev = resistance[1]
float _supPrev = support[1]
srBreakUpEvent = barstate.isconfirmed and not na(_resPrev) and close > _resPrev + srBreakBuffer and close[1] <= _resPrev + srBreakBuffer
srBreakDnEvent = barstate.isconfirmed and not na(_supPrev) and close < _supPrev - srBreakBuffer and close[1] >= _supPrev - srBreakBuffer
float srBreakUpLevelNow = srBreakUpEvent ? _resPrev : na
float srBreakDnLevelNow = srBreakDnEvent ? _supPrev : na
if srBreakUpEvent
retestResistance := _resPrev
retestResistanceExpiry := bar_index + _cfg.v1429RetestZoneBarsEff
retestResistanceConsumed := false
if srBreakDnEvent
retestSupport := _supPrev
retestSupportExpiry := bar_index + _cfg.v1429RetestZoneBarsEff
retestSupportConsumed := false
if not na(retestResistanceExpiry) and bar_index > retestResistanceExpiry
retestResistance := na
retestResistanceExpiry := na
retestResistanceConsumed := false
if not na(retestSupportExpiry) and bar_index > retestSupportExpiry
retestSupport := na
retestSupportExpiry := na
retestSupportConsumed := false
// Helper: safe time indexing for lookback
// Draw the ranked major S/R zones.
var box resBox = na
var box supBox = na
float resTop = na
float resBot = na
float supTop = na
float supBot = na
int leftT_sr = compat_SR_f_time_back(_cfg.v1429SrLookbackEff)
int rightT = time
float v146SStructTolNow = ta.atr(14) * _cfg.v146SConfluenceTolAtr
bool v146SResistanceMerged = _cfg.v146SShowSignalZones and _cfg.v146SSupplyActive and not na(_cfg.v146SSupplyTop) and not na(_cfg.v146SSupplyBottom) and not na(resistance) and resistance >= _cfg.v146SSupplyBottom - v146SStructTolNow and resistance <= _cfg.v146SSupplyTop + v146SStructTolNow
bool v146SSupportMerged = _cfg.v146SShowSignalZones and _cfg.v146SDemandActive and not na(_cfg.v146SDemandTop) and not na(_cfg.v146SDemandBottom) and not na(support) and support >= _cfg.v146SDemandBottom - v146SStructTolNow and support <= _cfg.v146SDemandTop + v146SStructTolNow
if not na(resistance) and not v146SResistanceMerged
resTop := resistance + clusterDistance / 2
resBot := resistance - clusterDistance / 2
float _r4a5AtrNow = math.max(ta.atr(14), syminfo.mintick)
float _r4a5PriceDenom = math.max(math.abs(close), syminfo.mintick)
float _r4a5ResDistAtr = math.abs(resistance - close) / _r4a5AtrNow
float _r4a5ResDistPct = math.abs(resistance - close) / _r4a5PriceDenom * 100.0
bool _r4a5ResMacro = (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) and (_r4a5ResDistAtr > _cfg.v1429MacroZoneDistanceAtr or _r4a5ResDistPct > _cfg.v1429MacroZoneDistancePct)
bool _r4a5HideRes = _cfg.v1429HTFCleanStructure and _r4a5ResMacro
color _r4a5ResBorder = _r4a5ResMacro ? color.new(_cfg.colResBorder, 70) : _cfg.colResBorder
color _r4a5ResFill = _r4a5ResMacro ? color.new(_cfg.colResFill, 97) : _cfg.colResFill
if _r4a5HideRes
if not na(resBox)
box.delete(resBox)
resBox := na
else
if na(resBox)
resBox := box.new(left=leftT_sr, top=resTop, right=rightT, bottom=resBot,
xloc=xloc.bar_time, border_color=_r4a5ResBorder, bgcolor=_r4a5ResFill)
else
box.set_left(resBox, leftT_sr)
box.set_right(resBox, rightT)
box.set_top(resBox, resTop)
box.set_bottom(resBox, resBot)
box.set_border_color(resBox, _r4a5ResBorder)
box.set_bgcolor(resBox, _r4a5ResFill)
else
if not na(resBox)
box.delete(resBox)
resBox := na
if not na(support) and not v146SSupportMerged
supTop := support + clusterDistance / 2
supBot := support - clusterDistance / 2
float _r4a5AtrNow = math.max(ta.atr(14), syminfo.mintick)
float _r4a5PriceDenom = math.max(math.abs(close), syminfo.mintick)
float _r4a5SupDistAtr = math.abs(support - close) / _r4a5AtrNow
float _r4a5SupDistPct = math.abs(support - close) / _r4a5PriceDenom * 100.0
bool _r4a5SupMacro = (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) and (_r4a5SupDistAtr > _cfg.v1429MacroZoneDistanceAtr or _r4a5SupDistPct > _cfg.v1429MacroZoneDistancePct)
bool _r4a5HideSup = _cfg.v1429HTFCleanStructure and _r4a5SupMacro
color _r4a5SupBorder = _r4a5SupMacro ? color.new(_cfg.colSupBorder, 70) : _cfg.colSupBorder
color _r4a5SupFill = _r4a5SupMacro ? color.new(_cfg.colSupFill, 97) : _cfg.colSupFill
if _r4a5HideSup
if not na(supBox)
box.delete(supBox)
supBox := na
else
if na(supBox)
supBox := box.new(left=leftT_sr, top=supTop, right=rightT, bottom=supBot,
xloc=xloc.bar_time, border_color=_r4a5SupBorder, bgcolor=_r4a5SupFill)
else
box.set_left(supBox, leftT_sr)
box.set_right(supBox, rightT)
box.set_top(supBox, supTop)
box.set_bottom(supBox, supBot)
box.set_border_color(supBox, _r4a5SupBorder)
box.set_bgcolor(supBox, _r4a5SupFill)
else
if not na(supBox)
box.delete(supBox)
supBox := na
// Retest / flip zones use a one-shot stateful lifecycle.
var box retestResBox = na
var box retestSupBox = na
int leftT_retest = compat_SR_f_time_back(_cfg.v1429RetestZoneBarsEff)
if not na(retestResistance) and bar_index <= nz(retestResistanceExpiry, -1)
float rrTop = retestResistance + clusterDistance / 2
float rrBot = retestResistance - clusterDistance / 2
if na(retestResBox)
retestResBox := box.new(left=leftT_retest, top=rrTop, right=rightT, bottom=rrBot,
xloc=xloc.bar_time, border_color=_cfg.colRetestResBorder, bgcolor=_cfg.colRetestResFill)
else
box.set_left(retestResBox, leftT_retest)
box.set_right(retestResBox, rightT)
box.set_top(retestResBox, rrTop)
box.set_bottom(retestResBox, rrBot)
else
if not na(retestResBox)
box.delete(retestResBox)
retestResBox := na
if not na(retestSupport) and bar_index <= nz(retestSupportExpiry, -1)
float rsTop = retestSupport + clusterDistance / 2
float rsBot = retestSupport - clusterDistance / 2
if na(retestSupBox)
retestSupBox := box.new(left=leftT_retest, top=rsTop, right=rightT, bottom=rsBot,
xloc=xloc.bar_time, border_color=_cfg.colRetestSupBorder, bgcolor=_cfg.colRetestSupFill)
else
box.set_left(retestSupBox, leftT_retest)
box.set_right(retestSupBox, rightT)
box.set_top(retestSupBox, rsTop)
box.set_bottom(retestSupBox, rsBot)
else
if not na(retestSupBox)
box.delete(retestSupBox)
retestSupBox := na
isNearResistance = not na(resistance) and math.abs(resistance - close) <= clusterDistance
isNearSupport = not na(support) and math.abs(support - close) <= clusterDistance
isNearRetestResistance = not na(retestResistance) and bar_index <= nz(retestResistanceExpiry, -1) and math.abs(retestResistance - close) <= clusterDistance
isNearRetestSupport = not na(retestSupport) and bar_index <= nz(retestSupportExpiry, -1) and math.abs(retestSupport - close) <= clusterDistance
isBreakAboveResistance = not na(resistance) and close > resistance
isBreakBelowSupport = not na(support) and close < support
// Contextual permission variables used by Spring and secondary structure modules.
// The primary BUY/SELL engine does not use these as a direct veto.
allowBuy = na(resistance) ? true : (not isNearResistance or isBreakAboveResistance)
allowSell = na(support) ? true : (not isNearSupport or isBreakBelowSupport)
srRetestTol = ta.atr(14) * _cfg.srRetestTolMult
bool srRetestBullRaw = not na(retestResistance) and not retestResistanceConsumed and bar_index <= nz(retestResistanceExpiry, -1) and bar_index > nz(retestResistanceExpiry, bar_index) - _cfg.v1429RetestZoneBarsEff and (
_cfg.srRetestUseWick ? math.abs(low - retestResistance) <= srRetestTol : math.abs(close - retestResistance) <= srRetestTol
) and close >= retestResistance
bool srRetestBearRaw = not na(retestSupport) and not retestSupportConsumed and bar_index <= nz(retestSupportExpiry, -1) and bar_index > nz(retestSupportExpiry, bar_index) - _cfg.v1429RetestZoneBarsEff and (
_cfg.srRetestUseWick ? math.abs(high - retestSupport) <= srRetestTol : math.abs(close - retestSupport) <= srRetestTol
) and close <= retestSupport
srRetestBull = barstate.isconfirmed and srRetestBullRaw
srRetestBear = barstate.isconfirmed and srRetestBearRaw
if srRetestBull
retestResistanceConsumed := true
if srRetestBear
retestSupportConsumed := true
LegacySRResult.new(allowBuy, allowSell, clusterDistance, isNearResistance, isNearRetestResistance, isNearRetestSupport, isNearSupport, pivotH, pivotL, resistance, retestResistance, retestSupport, srBreakDnEvent, srBreakDnLevelNow, srBreakUpEvent, srBreakUpLevelNow, srResistanceSpan, srResistanceTouches, srRetestBear, srRetestBull, srSupportSpan, srSupportTouches, src, support)
// === TL COMPATIBILITY SERVICE ===
export type LegacyTLConfig
color colTLRes
color colTLSup
float pivotH
float pivotL
int pivotRight
float tlBreakBufferAtr
int tlMaxPivots
int tlMaxViolations
int tlMinTouches
float tlRetestTolAtr
float tlTouchTolAtr
bool v1429HTFCleanStructure
bool v1429HTFDaily
int v1429HTFProjectionBars
float v1429HTFTrendlineDisplayDistanceAtr
float v1429HTFTrendlineDisplayDistancePct
bool v1429HTFWeekly
bool v1429ShowDevelopingTLNow
int v1429TlFlipHoldBarsEff
int v1429TlLookbackEff
float v1429TlMaxDistanceEff
float v1429TlMaxSlopeEff
int v1429TlMinSpanEff
int v1429TlRetestWindowEff
int v1429TlTouchGapEff
bool v1429ViewContext
bool v1429ViewDetailed
float v146LNewStructureAtr
float v146LTlFamilyPriceTolAtr
float v146LTlFamilySlopeTol
float v146LTlRoleToleranceAtr
export type LegacyTLResult
line developing_res_tl
line developing_sup_tl
int domResNewB
int domResNewT
float domResNewY
int domResOldB
int domResOldT
float domResOldY
int domResTouches
int domSupNewB
int domSupNewT
float domSupNewY
int domSupOldB
int domSupOldT
float domSupOldY
int domSupTouches
float res_tl_y
float sup_tl_y
bool tlBreakDnFailedNow
bool tlBreakUpFailedNow
bool tlDnActive
line tlFlipResistanceLine
line tlFlipSupportLine
bool tlUpActive
bool trend_break_dn
bool trend_break_up
bool trend_retest_dn
bool trend_retest_up
bool v14291Visual01Arg00
color v14291Visual01Arg03
bool v14291Visual02Arg00
color v14291Visual02Arg03
bool v14291Visual03Arg00
color v14291Visual03Arg03
bool v14291Visual04Arg00
color v14291Visual04Arg03
compat_TL_f_best_dominant_tl(LegacyTLConfig _cfg, array<float> vals, array<int> bars, array<int> times, bool isResistance, float atrNow, int skipOldB, int skipNewB, float retiredFamilyLevel, float retiredFamilySlope, int retiredFamilyBreakBar, bool postBreakLock, int minTouchesRequired) =>
int bestOldT = na
float bestOldY = na
int bestNewT = na
float bestNewY = na
int bestOldB = na
int bestNewB = na
float bestScore = -1.0e10
int bestTouches = 0
int n = array.size(vals)
float tol = atrNow * _cfg.tlTouchTolAtr
if n >= 2 and atrNow > 0 and not postBreakLock
for i = 0 to n - 2
int newB = array.get(bars, i)
float newY = array.get(vals, i)
int newT = array.get(times, i)
for j = i + 1 to n - 1
int oldB = array.get(bars, j)
float oldY = array.get(vals, j)
int oldT = array.get(times, j)
int span = newB - oldB
bool retiredExact = not na(skipOldB) and not na(skipNewB) and oldB == skipOldB and newB == skipNewB
if span >= _cfg.v1429TlMinSpanEff and not retiredExact
float slope = (newY - oldY) / span
float slopeNorm = math.abs(slope) / math.max(atrNow, syminfo.mintick)
if slopeNorm <= _cfg.v1429TlMaxSlopeEff
int touches = 0
int violations = 0
int lastTouchB = na
for k = 0 to n - 1
int b = array.get(bars, k)
if b >= oldB
float v = array.get(vals, k)
float ly = oldY + slope * (b - oldB)
float d = v - ly
bool touch = math.abs(d) <= tol
if touch and (na(lastTouchB) or math.abs(b - lastTouchB) >= _cfg.v1429TlTouchGapEff)
touches += 1
lastTouchB := b
if isResistance and d > tol
violations += 1
if not isResistance and d < -tol
violations += 1
float yNow = oldY + slope * (bar_index - oldB)
float distAtr = math.abs(yNow - close) / math.max(atrNow, syminfo.mintick)
bool roleOK = isResistance ? yNow >= close - atrNow * _cfg.v146LTlRoleToleranceAtr : yNow <= close + atrNow * _cfg.v146LTlRoleToleranceAtr
float retiredProjectedNow = not na(retiredFamilyLevel) and not na(retiredFamilySlope) and not na(retiredFamilyBreakBar) ? retiredFamilyLevel + retiredFamilySlope * (bar_index - retiredFamilyBreakBar) : na
bool retiredFamilyFresh = not na(retiredFamilyBreakBar) and bar_index - retiredFamilyBreakBar <= _cfg.v1429TlLookbackEff
bool retiredFamily = retiredFamilyFresh and not na(retiredProjectedNow) and math.abs(yNow - retiredProjectedNow) <= atrNow * _cfg.v146LTlFamilyPriceTolAtr and math.abs(slope - retiredFamilySlope) / math.max(atrNow, syminfo.mintick) <= _cfg.v146LTlFamilySlopeTol
if touches >= minTouchesRequired and violations <= _cfg.tlMaxViolations and distAtr <= _cfg.v1429TlMaxDistanceEff and roleOK and not retiredFamily
float score = touches * 100.0 + math.min(span, _cfg.v1429TlLookbackEff) * 0.35 - violations * 80.0 - distAtr * 2.0 - slopeNorm * 20.0
if score > bestScore
bestScore := score
bestOldT := oldT
bestOldY := oldY
bestNewT := newT
bestNewY := newY
bestOldB := oldB
bestNewB := newB
bestTouches := touches
[bestOldT, bestOldY, bestNewT, bestNewY, bestOldB, bestNewB, bestScore, bestTouches]
compat_TL_f_v1429_line_y_from_points(_x1, _y1, _x2, _y2, _tNow) =>
int _dx = _x2 - _x1
float _slope = _dx != 0 ? (_y2 - _y1) / _dx : 0.0
_y1 + _slope * (_tNow - _x1)
compat_TL_f_v1429_apply_dom_tl_display(LegacyTLConfig _cfg, _lineId, _x1, _y1, _x2, _y2, _baseColor) =>
if not na(_lineId) and (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly)
float _atrNow = math.max(ta.atr(14), syminfo.mintick)
float _priceDenom = math.max(math.abs(close), syminfo.mintick)
float _yNow = compat_TL_f_v1429_line_y_from_points(_x1, _y1, _x2, _y2, time)
float _distAtr = math.abs(_yNow - close) / _atrNow
float _distPct = math.abs(_yNow - close) / _priceDenom * 100.0
bool _macro = _distAtr > _cfg.v1429HTFTrendlineDisplayDistanceAtr or _distPct > _cfg.v1429HTFTrendlineDisplayDistancePct
bool _hide = _cfg.v1429HTFCleanStructure and _macro
int _barMs = math.max(1, int(timeframe.in_seconds() * 1000.0))
float _displayEnvelope = math.max(_atrNow * _cfg.v1429HTFTrendlineDisplayDistanceAtr, _priceDenom * _cfg.v1429HTFTrendlineDisplayDistancePct / 100.0)
float _slopePerMs = _x2 != _x1 ? (_y2 - _y1) / (_x2 - _x1) : 0.0
float _slopePerBar = _slopePerMs * _barMs
int _safeBars = _cfg.v1429HTFProjectionBars
if math.abs(_slopePerBar) > syminfo.mintick * 0.01
float _roomInSlopeDir = _slopePerBar > 0 ? close + _displayEnvelope - _yNow : _yNow - (close - _displayEnvelope)
int _barsToEnvelope = int(math.floor(math.max(0.0, _roomInSlopeDir) / math.abs(_slopePerBar)))
_safeBars := math.max(0, math.min(_cfg.v1429HTFProjectionBars, _barsToEnvelope))
int _projectT = time + _barMs * _safeBars
if _hide
line.set_xy1(_lineId, time, close)
line.set_xy2(_lineId, time + _barMs, close)
line.set_color(_lineId, color.new(_baseColor, 100))
line.set_width(_lineId, 1)
line.set_extend(_lineId, extend.none)
else if _macro
line.set_xy1(_lineId, _x1, _y1)
line.set_xy2(_lineId, _x2, _y2)
line.set_color(_lineId, color.new(_baseColor, 72))
line.set_width(_lineId, 1)
line.set_style(_lineId, line.style_solid)
line.set_extend(_lineId, extend.none)
else
float _projectY = compat_TL_f_v1429_line_y_from_points(_x1, _y1, _x2, _y2, _projectT)
line.set_xy1(_lineId, _x1, _y1)
line.set_xy2(_lineId, _projectT, _projectY)
line.set_color(_lineId, _baseColor)
line.set_width(_lineId, 2)
line.set_style(_lineId, line.style_solid)
line.set_extend(_lineId, extend.none)
compat_TL_f_v1429_cap_aux_tl_projection(LegacyTLConfig _cfg, _lineId) =>
if not na(_lineId) and (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly)
int _x1 = line.get_x1(_lineId)
float _y1 = line.get_y1(_lineId)
int _x2 = line.get_x2(_lineId)
float _y2 = line.get_y2(_lineId)
int _barMs = math.max(1, int(timeframe.in_seconds() * 1000.0))
float _atrNow = math.max(ta.atr(14), syminfo.mintick)
float _priceDenom = math.max(math.abs(close), syminfo.mintick)
float _yNow = compat_TL_f_v1429_line_y_from_points(_x1, _y1, _x2, _y2, time)
float _displayEnvelope = math.max(_atrNow * _cfg.v1429HTFTrendlineDisplayDistanceAtr, _priceDenom * _cfg.v1429HTFTrendlineDisplayDistancePct / 100.0)
float _slopePerMs = _x2 != _x1 ? (_y2 - _y1) / (_x2 - _x1) : 0.0
float _slopePerBar = _slopePerMs * _barMs
int _safeBars = _cfg.v1429HTFProjectionBars
if math.abs(_slopePerBar) > syminfo.mintick * 0.01
float _roomInSlopeDir = _slopePerBar > 0 ? close + _displayEnvelope - _yNow : _yNow - (close - _displayEnvelope)
int _barsToEnvelope = int(math.floor(math.max(0.0, _roomInSlopeDir) / math.abs(_slopePerBar)))
_safeBars := math.max(0, math.min(_cfg.v1429HTFProjectionBars, _barsToEnvelope))
int _projectT = time + _barMs * _safeBars
float _projectY = compat_TL_f_v1429_line_y_from_points(_x1, _y1, _x2, _y2, _projectT)
line.set_xy2(_lineId, _projectT, _projectY)
line.set_extend(_lineId, extend.none)
export lineYAtTime(line line_id, int t_now) =>
x1 = line.get_x1(line_id)
y1 = line.get_y1(line_id)
x2 = line.get_x2(line_id)
y2 = line.get_y2(line_id)
dx = x2 - x1
dy = y2 - y1
slope = dx != 0 ? dy / dx : 0.0
y1 + slope * (t_now - x1)
//@function v14.31 TL extraction. Call once per chart execution at original evaluation point.
export legacyTL(LegacyTLConfig _cfg) =>
// =============================================================================
// [B] MAJOR TRENDLINE ENGINE — CONFIRMED + DEVELOPING LIFECYCLE
// =============================================================================
// The trendline engine ranks causal candidate
// lines built from confirmed pivots. A dominant line earns authority through
// independent touches, span, low violation count and reasonable price relevance.
var float[] trend_pivothighs = array.new<float>()
var int[] trend_ph_times = array.new<int>()
var int[] trend_ph_bars = array.new<int>()
var float[] trend_pivotlows = array.new<float>()
var int[] trend_pl_times = array.new<int>()
var int[] trend_pl_bars = array.new<int>()
ph = _cfg.pivotH
pl = _cfg.pivotL
if not na(ph)
array.unshift(trend_pivothighs, ph)
array.unshift(trend_ph_times, time[_cfg.pivotRight])
array.unshift(trend_ph_bars, bar_index - _cfg.pivotRight)
if not na(pl)
array.unshift(trend_pivotlows, pl)
array.unshift(trend_pl_times, time[_cfg.pivotRight])
array.unshift(trend_pl_bars, bar_index - _cfg.pivotRight)
while array.size(trend_ph_bars) > 0 and (bar_index - array.get(trend_ph_bars, array.size(trend_ph_bars) - 1) > _cfg.v1429TlLookbackEff or array.size(trend_ph_bars) > _cfg.tlMaxPivots)
array.pop(trend_pivothighs)
array.pop(trend_ph_times)
array.pop(trend_ph_bars)
while array.size(trend_pl_bars) > 0 and (bar_index - array.get(trend_pl_bars, array.size(trend_pl_bars) - 1) > _cfg.v1429TlLookbackEff or array.size(trend_pl_bars) > _cfg.tlMaxPivots)
array.pop(trend_pivotlows)
array.pop(trend_pl_times)
array.pop(trend_pl_bars)
var line last_res_tl = na
var line last_sup_tl = na
// Developing boundaries are display-only. They never feed res_tl_y/sup_tl_y,
// therefore they have zero break/retest/trap/score/signal authority.
var line developing_res_tl = na
var line developing_sup_tl = na
var int domResOldT = na
var float domResOldY = na
var int domResNewT = na
var float domResNewY = na
var int domResOldB = na
var int domResNewB = na
var int domResTouches = 0
var int domSupOldT = na
var float domSupOldY = na
var int domSupNewT = na
var float domSupNewY = na
var int domSupOldB = na
var int domSupNewB = na
var int domSupTouches = 0
// Trendline lifecycle memory. A successfully broken dominant boundary is
// retired from its old role so it cannot immediately resurrect from the same pivots.
var int retiredResOldB = na
var int retiredResNewB = na
var int retiredSupOldB = na
var int retiredSupNewB = na
// Trendline family memory: exact anchors are not enough because A-B can resurrect as A-C.
// Store the broken boundary in price/slope space and lock its old role until new structure forms.
var float retiredResFamilyLevel = na
var float retiredResFamilySlope = na
var int retiredResFamilyBreakBar = na
var float retiredSupFamilyLevel = na
var float retiredSupFamilySlope = na
var int retiredSupFamilyBreakBar = na
var bool resPostBreakLock = false
var float resPostBreakLevel = na
var int resPostBreakBar = na
var bool supPostBreakLock = false
var float supPostBreakLevel = na
var int supPostBreakBar = na
var bool tlUpActive = false
var float tlUpBreakLevel = na
var int tlUpBreakBar = na
var int tlUpOldT = na
var float tlUpOldY = na
var int tlUpNewT = na
var float tlUpNewY = na
var int tlUpOldB = na
var int tlUpNewB = na
var bool tlDnActive = false
var float tlDnBreakLevel = na
var int tlDnBreakBar = na
var int tlDnOldT = na
var float tlDnOldY = na
var int tlDnNewT = na
var float tlDnNewY = na
var int tlDnOldB = na
var int tlDnNewB = na
var line tlFlipSupportLine = na
var int tlFlipSupportBornBar = na
var line tlFlipResistanceLine = na
var int tlFlipResistanceBornBar = na
// Post-break structural lock. Old resistance/support families cannot immediately
// reappear after a decisive break. A genuinely new confirmed pivot beyond the broken
// region releases the lock; family matching below still prevents the old geometry from returning.
if barstate.isconfirmed
float _tlAtrNow = ta.atr(14)
if resPostBreakLock and not na(ph) and not na(resPostBreakLevel) and (bar_index - _cfg.pivotRight) > nz(resPostBreakBar, bar_index) and ph > resPostBreakLevel + _tlAtrNow * _cfg.v146LNewStructureAtr
resPostBreakLock := false
if supPostBreakLock and not na(pl) and not na(supPostBreakLevel) and (bar_index - _cfg.pivotRight) > nz(supPostBreakBar, bar_index) and pl < supPostBreakLevel - _tlAtrNow * _cfg.v146LNewStructureAtr
supPostBreakLock := false
// Re-select only when a new confirmed pivot arrives and no break decision is pending.
// This prevents a newly formed pivot from changing the exact boundary being tested.
if barstate.isconfirmed and not tlUpActive and (not na(ph) or na(last_res_tl))
[rOldT, rOldY, rNewT, rNewY, rOldB, rNewB, rScore, rTouches] = compat_TL_f_best_dominant_tl(_cfg, trend_pivothighs, trend_ph_bars, trend_ph_times, true, ta.atr(14), retiredResOldB, retiredResNewB, retiredResFamilyLevel, retiredResFamilySlope, retiredResFamilyBreakBar, resPostBreakLock, _cfg.tlMinTouches)
if not na(rOldT)
domResOldT := rOldT
domResOldY := rOldY
domResNewT := rNewT
domResNewY := rNewY
domResOldB := rOldB
domResNewB := rNewB
domResTouches := rTouches
if not na(developing_res_tl)
line.delete(developing_res_tl)
developing_res_tl := na
if na(last_res_tl)
last_res_tl := line.new(x1=domResOldT, y1=domResOldY, x2=domResNewT, y2=domResNewY, xloc=xloc.bar_time, color=_cfg.colTLRes, width=2, extend=extend.right)
else
line.set_xy1(last_res_tl, domResOldT, domResOldY)
line.set_xy2(last_res_tl, domResNewT, domResNewY)
line.set_color(last_res_tl, _cfg.colTLRes)
line.set_width(last_res_tl, 2)
line.set_style(last_res_tl, line.style_solid)
line.set_extend(last_res_tl, extend.right)
else if _cfg.v1429ShowDevelopingTLNow and _cfg.tlMinTouches > 2
[drOldT, drOldY, drNewT, drNewY, drOldB, drNewB, drScore, drTouches] = compat_TL_f_best_dominant_tl(_cfg, trend_pivothighs, trend_ph_bars, trend_ph_times, true, ta.atr(14), retiredResOldB, retiredResNewB, retiredResFamilyLevel, retiredResFamilySlope, retiredResFamilyBreakBar, resPostBreakLock, 2)
if not na(drOldT) and drTouches < _cfg.tlMinTouches
if na(developing_res_tl)
developing_res_tl := line.new(x1=drOldT, y1=drOldY, x2=drNewT, y2=drNewY, xloc=xloc.bar_time, color=color.new(_cfg.colTLRes, 45), width=1, style=line.style_dashed, extend=(_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) ? extend.none : extend.right)
else
line.set_xy1(developing_res_tl, drOldT, drOldY)
line.set_xy2(developing_res_tl, drNewT, drNewY)
line.set_color(developing_res_tl, color.new(_cfg.colTLRes, 45))
line.set_width(developing_res_tl, 1)
line.set_style(developing_res_tl, line.style_dashed)
line.set_extend(developing_res_tl, (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) ? extend.none : extend.right)
else if not na(developing_res_tl)
line.delete(developing_res_tl)
developing_res_tl := na
else if not na(developing_res_tl)
line.delete(developing_res_tl)
developing_res_tl := na
if barstate.isconfirmed and not tlDnActive and (not na(pl) or na(last_sup_tl))
[sOldT, sOldY, sNewT, sNewY, sOldB, sNewB, sScore, sTouches] = compat_TL_f_best_dominant_tl(_cfg, trend_pivotlows, trend_pl_bars, trend_pl_times, false, ta.atr(14), retiredSupOldB, retiredSupNewB, retiredSupFamilyLevel, retiredSupFamilySlope, retiredSupFamilyBreakBar, supPostBreakLock, _cfg.tlMinTouches)
if not na(sOldT)
domSupOldT := sOldT
domSupOldY := sOldY
domSupNewT := sNewT
domSupNewY := sNewY
domSupOldB := sOldB
domSupNewB := sNewB
domSupTouches := sTouches
if not na(developing_sup_tl)
line.delete(developing_sup_tl)
developing_sup_tl := na
if na(last_sup_tl)
last_sup_tl := line.new(x1=domSupOldT, y1=domSupOldY, x2=domSupNewT, y2=domSupNewY, xloc=xloc.bar_time, color=_cfg.colTLSup, width=2, extend=extend.right)
else
line.set_xy1(last_sup_tl, domSupOldT, domSupOldY)
line.set_xy2(last_sup_tl, domSupNewT, domSupNewY)
line.set_color(last_sup_tl, _cfg.colTLSup)
line.set_width(last_sup_tl, 2)
line.set_style(last_sup_tl, line.style_solid)
line.set_extend(last_sup_tl, extend.right)
else if _cfg.v1429ShowDevelopingTLNow and _cfg.tlMinTouches > 2
[dsOldT, dsOldY, dsNewT, dsNewY, dsOldB, dsNewB, dsScore, dsTouches] = compat_TL_f_best_dominant_tl(_cfg, trend_pivotlows, trend_pl_bars, trend_pl_times, false, ta.atr(14), retiredSupOldB, retiredSupNewB, retiredSupFamilyLevel, retiredSupFamilySlope, retiredSupFamilyBreakBar, supPostBreakLock, 2)
if not na(dsOldT) and dsTouches < _cfg.tlMinTouches
if na(developing_sup_tl)
developing_sup_tl := line.new(x1=dsOldT, y1=dsOldY, x2=dsNewT, y2=dsNewY, xloc=xloc.bar_time, color=color.new(_cfg.colTLSup, 45), width=1, style=line.style_dashed, extend=(_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) ? extend.none : extend.right)
else
line.set_xy1(developing_sup_tl, dsOldT, dsOldY)
line.set_xy2(developing_sup_tl, dsNewT, dsNewY)
line.set_color(developing_sup_tl, color.new(_cfg.colTLSup, 45))
line.set_width(developing_sup_tl, 1)
line.set_style(developing_sup_tl, line.style_dashed)
line.set_extend(developing_sup_tl, (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) ? extend.none : extend.right)
else if not na(developing_sup_tl)
line.delete(developing_sup_tl)
developing_sup_tl := na
else if not na(developing_sup_tl)
line.delete(developing_sup_tl)
developing_sup_tl := na
// Expire genuinely stale lines, but otherwise allow a strong older line to remain
// dormant and reactivate when price comes back to it.
if not na(domResOldB) and bar_index - domResOldB > _cfg.v1429TlLookbackEff
if not na(last_res_tl)
line.delete(last_res_tl)
last_res_tl := na
domResOldB := na
if not na(domSupOldB) and bar_index - domSupOldB > _cfg.v1429TlLookbackEff
if not na(last_sup_tl)
line.delete(last_sup_tl)
last_sup_tl := na
domSupOldB := na
// Compute structural line value from frozen anchor data, independent
// of how the line object is clipped, labelled or hidden for presentation.
// Apply finite, slope-aware and scale-aware Daily/Weekly projection to a dominant line.
// Structural anchors/slope remain untouched. Only the drawing endpoint is constrained.
// Macro lines in Standard/Detailed remain visible as their frozen anchor segment,
// rather than being projected into extreme future prices that can destroy chart scale.
// Cap developing/flipped HTF lines using the same scale envelope.
// These are display-only/lifecycle drawings; their underlying structural state is unchanged.
// Helper: get y-value of a TIME-anchored line at current TIME
// Developing lines are visual hypotheses only. If price decisively moves
// through the role they were depicting before another pivot arrives, retire the
// visual immediately rather than leaving an obviously wrong dashed boundary.
if not _cfg.v1429ShowDevelopingTLNow
if not na(developing_res_tl)
line.delete(developing_res_tl)
developing_res_tl := na
if not na(developing_sup_tl)
line.delete(developing_sup_tl)
developing_sup_tl := na
else
float _devAtr = ta.atr(14)
if not na(developing_res_tl)
float _devResY = lineYAtTime(developing_res_tl, time)
if _devResY < close - _devAtr * _cfg.v146LTlRoleToleranceAtr
line.delete(developing_res_tl)
developing_res_tl := na
if not na(developing_sup_tl)
float _devSupY = lineYAtTime(developing_sup_tl, time)
if _devSupY > close + _devAtr * _cfg.v146LTlRoleToleranceAtr
line.delete(developing_sup_tl)
developing_sup_tl := na
res_tl_y = na(last_res_tl) or na(domResOldT) or na(domResNewT) ? na : compat_TL_f_v1429_line_y_from_points(domResOldT, domResOldY, domResNewT, domResNewY, time)
sup_tl_y = na(last_sup_tl) or na(domSupOldT) or na(domSupNewT) ? na : compat_TL_f_v1429_line_y_from_points(domSupOldT, domSupOldY, domSupNewT, domSupNewY, time)
res_tl_y_1 = na(last_res_tl) or na(domResOldT) or na(domResNewT) ? na : compat_TL_f_v1429_line_y_from_points(domResOldT, domResOldY, domResNewT, domResNewY, time[1])
sup_tl_y_1 = na(last_sup_tl) or na(domSupOldT) or na(domSupNewT) ? na : compat_TL_f_v1429_line_y_from_points(domSupOldT, domSupOldY, domSupNewT, domSupNewY, time[1])
// Presentation is applied only after the unchanged structural y-values are frozen.
compat_TL_f_v1429_apply_dom_tl_display(_cfg, last_res_tl, domResOldT, domResOldY, domResNewT, domResNewY, _cfg.colTLRes)
compat_TL_f_v1429_apply_dom_tl_display(_cfg, last_sup_tl, domSupOldT, domSupOldY, domSupNewT, domSupNewY, _cfg.colTLSup)
// HTF developing lines remain the exact two-pivot segment; no future projection.
// Detailed-mode role identity. These are two mutable labels only and do not
// create a historical trail. They make clear that independent R-TL and S-TL
// boundaries are not an automatically calculated channel.
var label v1429HTFResRoleLabel = na
var label v1429HTFSupRoleLabel = na
if barstate.islast
bool _r4a5ShowRoleLabels = (_cfg.v1429HTFDaily or _cfg.v1429HTFWeekly) and _cfg.v1429ViewDetailed
int _r4a5RoleBarMs = int(timeframe.in_seconds() * 1000.0)
int _r4a5RoleX = time + _r4a5RoleBarMs
if _r4a5ShowRoleLabels and not na(last_res_tl) and not na(domResOldT) and not na(domResNewT)
float _r4a5ResLabelY = compat_TL_f_v1429_line_y_from_points(domResOldT, domResOldY, domResNewT, domResNewY, _r4a5RoleX)
string _r4a5ResLabelText = "R-TL" + (domResTouches > 0 ? " · " + str.tostring(domResTouches) + "T" : "")
if na(v1429HTFResRoleLabel)
v1429HTFResRoleLabel := label.new(x=_r4a5RoleX, y=_r4a5ResLabelY, text=_r4a5ResLabelText, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(_cfg.colTLRes, 86), textcolor=_cfg.colTLRes, size=size.tiny)
else
label.set_xy(v1429HTFResRoleLabel, _r4a5RoleX, _r4a5ResLabelY)
label.set_text(v1429HTFResRoleLabel, _r4a5ResLabelText)
label.set_color(v1429HTFResRoleLabel, color.new(_cfg.colTLRes, 86))
label.set_textcolor(v1429HTFResRoleLabel, _cfg.colTLRes)
else if not na(v1429HTFResRoleLabel)
label.delete(v1429HTFResRoleLabel)
v1429HTFResRoleLabel := na
if _r4a5ShowRoleLabels and not na(last_sup_tl) and not na(domSupOldT) and not na(domSupNewT)
float _r4a5SupLabelY = compat_TL_f_v1429_line_y_from_points(domSupOldT, domSupOldY, domSupNewT, domSupNewY, _r4a5RoleX)
string _r4a5SupLabelText = "S-TL" + (domSupTouches > 0 ? " · " + str.tostring(domSupTouches) + "T" : "")
if na(v1429HTFSupRoleLabel)
v1429HTFSupRoleLabel := label.new(x=_r4a5RoleX, y=_r4a5SupLabelY, text=_r4a5SupLabelText, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(_cfg.colTLSup, 86), textcolor=_cfg.colTLSup, size=size.tiny)
else
label.set_xy(v1429HTFSupRoleLabel, _r4a5RoleX, _r4a5SupLabelY)
label.set_text(v1429HTFSupRoleLabel, _r4a5SupLabelText)
label.set_color(v1429HTFSupRoleLabel, color.new(_cfg.colTLSup, 86))
label.set_textcolor(v1429HTFSupRoleLabel, _cfg.colTLSup)
else if not na(v1429HTFSupRoleLabel)
label.delete(v1429HTFSupRoleLabel)
v1429HTFSupRoleLabel := na
float tlBreakBuffer = ta.atr(14) * _cfg.tlBreakBufferAtr
float tlRetestTol = ta.atr(14) * _cfg.tlRetestTolAtr
// One-shot BREAK -> RETEST / FAILED-BREAK lifecycle with role-flip/retirement.
trend_break_up = false
trend_break_dn = false
trend_retest_up = false
trend_retest_dn = false
bool tlBreakUpFailedNow = false
bool tlBreakDnFailedNow = false
if barstate.isconfirmed
bool rawBreakUp = not na(res_tl_y) and not na(res_tl_y_1) and close > res_tl_y + tlBreakBuffer and close[1] <= res_tl_y_1 + tlBreakBuffer
bool rawBreakDn = not na(sup_tl_y) and not na(sup_tl_y_1) and close < sup_tl_y - tlBreakBuffer and close[1] >= sup_tl_y_1 - tlBreakBuffer
if rawBreakUp and not tlUpActive
trend_break_up := true
tlUpActive := true
tlUpBreakLevel := res_tl_y
tlUpBreakBar := bar_index
tlUpOldT := domResOldT
tlUpOldY := domResOldY
tlUpNewT := domResNewT
tlUpNewY := domResNewY
tlUpOldB := domResOldB
tlUpNewB := domResNewB
if rawBreakDn and not tlDnActive
trend_break_dn := true
tlDnActive := true
tlDnBreakLevel := sup_tl_y
tlDnBreakBar := bar_index
tlDnOldT := domSupOldT
tlDnOldY := domSupOldY
tlDnNewT := domSupNewT
tlDnNewY := domSupNewY
tlDnOldB := domSupOldB
tlDnNewB := domSupNewB
if tlUpActive and bar_index > nz(tlUpBreakBar, bar_index)
bool touchUp = low <= tlUpBreakLevel + tlRetestTol and high >= tlUpBreakLevel - tlRetestTol
if touchUp and close >= tlUpBreakLevel
trend_retest_up := true
// Successful resistance break + hold: old resistance is retired and
// shown temporarily as flipped support, never resurrected as red resistance.
retiredResOldB := tlUpOldB
retiredResNewB := tlUpNewB
int _resSpan = nz(tlUpNewB, 0) - nz(tlUpOldB, 0)
retiredResFamilySlope := _resSpan != 0 ? (tlUpNewY - tlUpOldY) / _resSpan : 0.0
retiredResFamilyLevel := tlUpBreakLevel
retiredResFamilyBreakBar := tlUpBreakBar
resPostBreakLock := true
resPostBreakLevel := tlUpBreakLevel
resPostBreakBar := tlUpBreakBar
if not na(tlFlipSupportLine)
line.delete(tlFlipSupportLine)
if not na(tlUpOldT) and not na(tlUpNewT)
tlFlipSupportLine := line.new(x1=tlUpOldT, y1=tlUpOldY, x2=tlUpNewT, y2=tlUpNewY, xloc=xloc.bar_time, color=color.new(_cfg.colTLSup, 35), width=1, style=line.style_dashed, extend=extend.right)
tlFlipSupportBornBar := bar_index
if not na(last_res_tl)
line.delete(last_res_tl)
last_res_tl := na
domResOldB := na
tlUpActive := false
else if close < tlUpBreakLevel - tlRetestTol
tlBreakUpFailedNow := true
tlUpActive := false
else if bar_index - tlUpBreakBar > _cfg.v1429TlRetestWindowEff
// Break held without a retest. Retire the obsolete resistance, but do
// not invent a support flip until the market actually retests it.
retiredResOldB := tlUpOldB
retiredResNewB := tlUpNewB
int _resSpan = nz(tlUpNewB, 0) - nz(tlUpOldB, 0)
retiredResFamilySlope := _resSpan != 0 ? (tlUpNewY - tlUpOldY) / _resSpan : 0.0
retiredResFamilyLevel := tlUpBreakLevel
retiredResFamilyBreakBar := tlUpBreakBar
resPostBreakLock := true
resPostBreakLevel := tlUpBreakLevel
resPostBreakBar := tlUpBreakBar
if not na(last_res_tl)
line.delete(last_res_tl)
last_res_tl := na
domResOldB := na
tlUpActive := false
if tlDnActive and bar_index > nz(tlDnBreakBar, bar_index)
bool touchDn = high >= tlDnBreakLevel - tlRetestTol and low <= tlDnBreakLevel + tlRetestTol
if touchDn and close <= tlDnBreakLevel
trend_retest_dn := true
retiredSupOldB := tlDnOldB
retiredSupNewB := tlDnNewB
int _supSpan = nz(tlDnNewB, 0) - nz(tlDnOldB, 0)
retiredSupFamilySlope := _supSpan != 0 ? (tlDnNewY - tlDnOldY) / _supSpan : 0.0
retiredSupFamilyLevel := tlDnBreakLevel
retiredSupFamilyBreakBar := tlDnBreakBar
supPostBreakLock := true
supPostBreakLevel := tlDnBreakLevel
supPostBreakBar := tlDnBreakBar
if not na(tlFlipResistanceLine)
line.delete(tlFlipResistanceLine)
if not na(tlDnOldT) and not na(tlDnNewT)
tlFlipResistanceLine := line.new(x1=tlDnOldT, y1=tlDnOldY, x2=tlDnNewT, y2=tlDnNewY, xloc=xloc.bar_time, color=color.new(_cfg.colTLRes, 35), width=1, style=line.style_dashed, extend=extend.right)
tlFlipResistanceBornBar := bar_index
if not na(last_sup_tl)
line.delete(last_sup_tl)
last_sup_tl := na
domSupOldB := na
tlDnActive := false
else if close > tlDnBreakLevel + tlRetestTol
tlBreakDnFailedNow := true
tlDnActive := false
else if bar_index - tlDnBreakBar > _cfg.v1429TlRetestWindowEff
retiredSupOldB := tlDnOldB
retiredSupNewB := tlDnNewB
int _supSpan = nz(tlDnNewB, 0) - nz(tlDnOldB, 0)
retiredSupFamilySlope := _supSpan != 0 ? (tlDnNewY - tlDnOldY) / _supSpan : 0.0
retiredSupFamilyLevel := tlDnBreakLevel
retiredSupFamilyBreakBar := tlDnBreakBar
supPostBreakLock := true
supPostBreakLevel := tlDnBreakLevel
supPostBreakBar := tlDnBreakBar
if not na(last_sup_tl)
line.delete(last_sup_tl)
last_sup_tl := na
domSupOldB := na
tlDnActive := false
// Flipped boundaries remain finite on 1D/1W so their short contextual
// lifecycle is visible without years of forward projection.
compat_TL_f_v1429_cap_aux_tl_projection(_cfg, tlFlipSupportLine)
compat_TL_f_v1429_cap_aux_tl_projection(_cfg, tlFlipResistanceLine)
// Flipped boundaries are contextual only. Retire them when invalidated or stale.
if not na(tlFlipSupportLine)
float _flipSupY = lineYAtTime(tlFlipSupportLine, time)
if close < _flipSupY - tlRetestTol or bar_index - nz(tlFlipSupportBornBar, bar_index) > _cfg.v1429TlFlipHoldBarsEff
line.delete(tlFlipSupportLine)
tlFlipSupportLine := na
tlFlipSupportBornBar := na
if not na(tlFlipResistanceLine)
float _flipResY = lineYAtTime(tlFlipResistanceLine, time)
if close > _flipResY + tlRetestTol or bar_index - nz(tlFlipResistanceBornBar, bar_index) > _cfg.v1429TlFlipHoldBarsEff
line.delete(tlFlipResistanceLine)
tlFlipResistanceLine := na
tlFlipResistanceBornBar := na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual01Arg00 = _cfg.v1429ViewContext and trend_break_up
color v14291Visual01Arg03 = color.aqua
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual02Arg00 = _cfg.v1429ViewContext and trend_break_dn
color v14291Visual02Arg03 = color.fuchsia
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual03Arg00 = _cfg.v1429ViewContext and trend_retest_up
color v14291Visual03Arg03 = color.teal
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual04Arg00 = _cfg.v1429ViewContext and trend_retest_dn
color v14291Visual04Arg03 = color.purple
LegacyTLResult.new(developing_res_tl, developing_sup_tl, domResNewB, domResNewT, domResNewY, domResOldB, domResOldT, domResOldY, domResTouches, domSupNewB, domSupNewT, domSupNewY, domSupOldB, domSupOldT, domSupOldY, domSupTouches, res_tl_y, sup_tl_y, tlBreakDnFailedNow, tlBreakUpFailedNow, tlDnActive, tlFlipResistanceLine, tlFlipSupportLine, tlUpActive, trend_break_dn, trend_break_up, trend_retest_dn, trend_retest_up, v14291Visual01Arg00, v14291Visual01Arg03, v14291Visual02Arg00, v14291Visual02Arg03, v14291Visual03Arg00, v14291Visual03Arg03, v14291Visual04Arg00, v14291Visual04Arg03)
// === SMS COMPATIBILITY SERVICE ===
export type LegacySMSConfig
color smsBearCol
color smsBullCol
int smsCandleLen
color smsDiscCol
bool smsEnable
int smsPrd
color smsPremCol
int smsResp
bool smsShowBOSLabel
bool smsShowBear
bool smsShowBull
bool smsShowDonch
bool smsShowEQ
bool smsShowPD
bool smsShowStructCand
bool smsUseCloseBreak
bool smsUseResp
bool v1429ViewContext
bool v1429ViewFullStructure
bool v146SDetailed
export type LegacySMSResult
bool smsBmsDn
bool smsBmsUp
bool smsChochDn
bool smsChochUp
float smsDn
int smsPos
bool smsSmsDn
bool smsSmsUp
float smsUp
float v14291Visual05Arg00
color v14291Visual05Arg02
float v14291Visual06Arg00
color v14291Visual06Arg02
float v14291Visual07Arg00
float v14291Visual08Arg00
float v14291Visual09Arg00
float v14291Visual10Arg00
float v14291Visual11Arg00
float v14291Visual12Arg00
color v14291Visual13Arg02
color v14291Visual14Arg02
color v14291Visual15Arg02
float v14291Visual16Arg00
float v14291Visual16Arg01
float v14291Visual16Arg02
float v14291Visual16Arg03
color v14291Visual16Arg05
color v14291Visual16Arg06
color v14291Visual16Arg07
compat_SMS_f_lbl(_t, _y, _txt, _col, _down) =>
label.new(_t, _y, _txt, xloc=xloc.bar_time, textcolor=_col,
style=_down ? label.style_label_down : label.style_label_up,
color=color.new(color.black, 100), size=size.tiny)
compat_SMS_f_line(_t1, _t2, _y, _col) =>
line.new(_t1, _y, _t2, _y, xloc=xloc.bar_time, color=_col, width=1)
compat_SMS_f_center_time(_ta, _tb) =>
int(math.round((float(_ta) + float(_tb)) * 0.5))
compat_SMS_f_don_candle(_hi, _lo, _cl, _src, _len) =>
donH = ta.highest(_hi, _len)
donL = ta.lowest(_lo, _len)
denom = math.max(donH - donL, syminfo.mintick)
norm = (_cl - donL) / denom
var float out = na
out := (norm * _src) + (1.0 - norm) * nz(out[1], _src)
out
//@function v14.31 SMS extraction. Call once per chart execution at original evaluation point.
export legacySMS(LegacySMSConfig _cfg) =>
// --- Core state
var float smsUp = na
var float smsDn = na
var int smsIUp = na
var int smsIDn = na
var int smsPos = 0 // 0 neutral, >0 bullish legs, <0 bearish legs
// --- Events (bar-scoped)
smsChochUp = false
smsSmsUp = false
smsBmsUp = false
smsBosUp = false
smsChochDn = false
smsSmsDn = false
smsBmsDn = false
smsBosDn = false
// Time-anchored labels/lines (so they stay stable)
// --- Update range pivots
if _cfg.smsEnable
smsUp := na(smsUp[1]) ? high : math.max(smsUp[1], high)
smsDn := na(smsDn[1]) ? low : math.min(smsDn[1], low)
pHi = ta.pivothigh(high, _cfg.smsPrd, _cfg.smsPrd)
pLo = ta.pivotlow(low, _cfg.smsPrd, _cfg.smsPrd)
if not na(pHi)
smsUp := pHi
if not na(pLo)
smsDn := pLo
int look = _cfg.smsUseResp ? _cfg.smsResp : _cfg.smsPrd
// The CLOSE-break option directly controls
// structural break events. Range pivots still update from wick extremes.
bool smsBullBreakEvent = _cfg.smsUseCloseBreak ? (not na(smsUp[1]) and close > smsUp[1] and close[1] <= smsUp[1]) : smsUp > nz(smsUp[1], smsUp)
bool smsBearBreakEvent = _cfg.smsUseCloseBreak ? (not na(smsDn[1]) and close < smsDn[1] and close[1] >= smsDn[1]) : smsDn < nz(smsDn[1], smsDn)
// --- Bull side structure
if smsBullBreakEvent
smsIUp := bar_index
prevIdx = nz(smsIUp[1], bar_index - _cfg.smsPrd)
// Convert indices -> times (stable)
tPrev = time[bar_index - prevIdx]
tNow = time
tC = compat_SMS_f_center_time(tPrev, tNow)
confOK = smsUp[1] == smsUp[look]
if smsPos <= 0
if _cfg.smsShowBull and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsUp[1], "CHoCH", _cfg.smsBullCol, true)
compat_SMS_f_line(tPrev, tNow, smsUp[1], _cfg.smsBullCol)
smsChochUp := true
smsPos := 1
else
if _cfg.smsShowBOSLabel and confOK
if _cfg.smsShowBull and _cfg.v146SDetailed and _cfg.v1429ViewFullStructure
compat_SMS_f_lbl(tC, smsUp[1], "BOS", color.new(_cfg.smsBullCol, 0), true)
smsBosUp := true
if smsPos == 1 and confOK
if _cfg.smsShowBull and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsUp[1], "SMS", _cfg.smsBullCol, true)
compat_SMS_f_line(tPrev, tNow, smsUp[1], _cfg.smsBullCol)
smsSmsUp := true
smsPos := 2
else if smsPos > 1 and confOK
bool _showBullBms = _cfg.v146SDetailed or smsPos == 2
if _cfg.smsShowBull and _showBullBms and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsUp[1], "BMS", _cfg.smsBullCol, true)
compat_SMS_f_line(tPrev, tNow, smsUp[1], _cfg.smsBullCol)
smsBmsUp := true
smsPos += 1
else if smsUp < nz(smsUp[1], smsUp)
smsIUp := bar_index - _cfg.smsPrd
// --- Bear side structure
if smsBearBreakEvent
smsIDn := bar_index
prevIdx = nz(smsIDn[1], bar_index - _cfg.smsPrd)
tPrev = time[bar_index - prevIdx]
tNow = time
tC = compat_SMS_f_center_time(tPrev, tNow)
confOK = smsDn[1] == smsDn[look]
if smsPos >= 0
if _cfg.smsShowBear and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsDn[1], "CHoCH", _cfg.smsBearCol, false)
compat_SMS_f_line(tPrev, tNow, smsDn[1], _cfg.smsBearCol)
smsChochDn := true
smsPos := -1
else
if _cfg.smsShowBOSLabel and confOK
if _cfg.smsShowBear and _cfg.v146SDetailed and _cfg.v1429ViewFullStructure
compat_SMS_f_lbl(tC, smsDn[1], "BOS", color.new(_cfg.smsBearCol, 0), false)
smsBosDn := true
if smsPos == -1 and confOK
if _cfg.smsShowBear and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsDn[1], "SMS", _cfg.smsBearCol, false)
compat_SMS_f_line(tPrev, tNow, smsDn[1], _cfg.smsBearCol)
smsSmsDn := true
smsPos := -2
else if smsPos < -1 and confOK
bool _showBearBms = _cfg.v146SDetailed or smsPos == -2
if _cfg.smsShowBear and _showBearBms and _cfg.v1429ViewContext
compat_SMS_f_lbl(tC, smsDn[1], "BMS", _cfg.smsBearCol, false)
compat_SMS_f_line(tPrev, tNow, smsDn[1], _cfg.smsBearCol)
smsBmsDn := true
smsPos -= 1
else if smsDn > nz(smsDn[1], smsDn)
smsIDn := bar_index - _cfg.smsPrd
// --- Premium/Discount zones from smsUp/smsDn
smsPremiumTop = _cfg.smsEnable ? (smsUp - (smsUp - smsDn) * 0.10) : na
smsPremiumBot = _cfg.smsEnable ? (smsUp - (smsUp - smsDn) * 0.25) : na
smsDiscountTop = _cfg.smsEnable ? (smsDn + (smsUp - smsDn) * 0.25) : na
smsDiscountBot = _cfg.smsEnable ? (smsDn + (smsUp - smsDn) * 0.10) : na
smsMidTop = _cfg.smsEnable ? (smsUp - (smsUp - smsDn) * 0.45) : na
smsMidBot = _cfg.smsEnable ? (smsDn + (smsUp - smsDn) * 0.45) : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual05Arg00 = _cfg.smsEnable and _cfg.smsShowDonch ? smsUp : na
color v14291Visual05Arg02 = color.new(_cfg.smsBearCol, 0)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual06Arg00 = _cfg.smsEnable and _cfg.smsShowDonch ? smsDn : na
color v14291Visual06Arg02 = color.new(_cfg.smsBullCol, 0)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual07Arg00 = _cfg.smsEnable and _cfg.smsShowPD ? smsPremiumTop : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual08Arg00 = _cfg.smsEnable and _cfg.smsShowPD ? smsPremiumBot : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual09Arg00 = _cfg.smsEnable and _cfg.smsShowPD ? smsDiscountTop : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual10Arg00 = _cfg.smsEnable and _cfg.smsShowPD ? smsDiscountBot : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual11Arg00 = _cfg.smsEnable and _cfg.smsShowPD and _cfg.smsShowEQ ? smsMidTop : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual12Arg00 = _cfg.smsEnable and _cfg.smsShowPD and _cfg.smsShowEQ ? smsMidBot : na
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
color v14291Visual13Arg02 = (_cfg.smsEnable and _cfg.smsShowPD and _cfg.v1429ViewContext) ? _cfg.smsPremCol : color(na)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
color v14291Visual14Arg02 = (_cfg.smsEnable and _cfg.smsShowPD and _cfg.v1429ViewContext) ? _cfg.smsDiscCol : color(na)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
color v14291Visual15Arg02 = (_cfg.smsEnable and _cfg.smsShowPD and _cfg.smsShowEQ and _cfg.v1429ViewContext) ? color.new(color.gray, 75) : color(na)
// --- Optional structure candle overlay (global scope plotcandle; gated by na series)
O2 = (_cfg.smsEnable and _cfg.smsShowStructCand) ? compat_SMS_f_don_candle(smsUp, smsDn, close, open, _cfg.smsCandleLen) : na
H2 = (_cfg.smsEnable and _cfg.smsShowStructCand) ? compat_SMS_f_don_candle(smsUp, smsDn, close, high, _cfg.smsCandleLen) : na
L2 = (_cfg.smsEnable and _cfg.smsShowStructCand) ? compat_SMS_f_don_candle(smsUp, smsDn, close, low, _cfg.smsCandleLen) : na
C2 = (_cfg.smsEnable and _cfg.smsShowStructCand) ? compat_SMS_f_don_candle(smsUp, smsDn, close, close, _cfg.smsCandleLen) : na
col2 = (_cfg.smsEnable and _cfg.smsShowStructCand) ? (C2 >= O2 ? color.lime : color.red) : color(na)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual16Arg00 = O2
float v14291Visual16Arg01 = H2
float v14291Visual16Arg02 = L2
float v14291Visual16Arg03 = C2
color v14291Visual16Arg05 = col2
color v14291Visual16Arg06 = col2
color v14291Visual16Arg07 = col2
LegacySMSResult.new(smsBmsDn, smsBmsUp, smsChochDn, smsChochUp, smsDn, smsPos, smsSmsDn, smsSmsUp, smsUp, v14291Visual05Arg00, v14291Visual05Arg02, v14291Visual06Arg00, v14291Visual06Arg02, v14291Visual07Arg00, v14291Visual08Arg00, v14291Visual09Arg00, v14291Visual10Arg00, v14291Visual11Arg00, v14291Visual12Arg00, v14291Visual13Arg02, v14291Visual14Arg02, v14291Visual15Arg02, v14291Visual16Arg00, v14291Visual16Arg01, v14291Visual16Arg02, v14291Visual16Arg03, v14291Visual16Arg05, v14291Visual16Arg06, v14291Visual16Arg07)
// === LIQUIDITY COMPATIBILITY SERVICE ===
export type LegacyLiquidityConfig
float candleRange
color colEQH
color colEQL
color colSOS
color colSOW
color colSweepBear
color colSweepBull
bool enableLiquidity
bool enableRelaxPools
bool enableSpringOverride
bool enableSpringPrimary
bool enableStrongSweepOverride
int lastSpringBuyBar
int lastSpringSellBar
int liqLookbackH
int liqMinMomConf
int liqMinTouches
int liqScorePts
float liqTolMult
float lowerWick
int obvBear
int obvBull
float pivotH
float pivotL
int pivotRight
float relaxTolScale
int relaxTouchDrop
float resistance
bool showLiquidityLines
bool showSOSLabels
bool showSweepMarkers
bool smsChochDn
bool smsChochUp
int sosScorePts
int sowScorePts
int springPrimaryDebounceBars
int springPrimaryMinMomConf
bool springPrimaryRequireCHoCH
bool springUseSR
int springVolLen
float springVolMult
float springWickRatio
int srMomBearCnt
int srMomBullCnt
float srRetestTolMult
float support
int sweepConfirmH
float sweepWickRatio
float upperWick
bool useCloseForSweep
bool v1429ViewContext
bool v1429ViewFullStructure
float v146LConsumedPoolLockAtr
float v146SConfluenceTolAtr
bool v146SDemandActive
float v146SDemandBottom
float v146SDemandTop
bool v146SDetailed
float v146SNewPoolTolAtr
bool v146SOneShotLiquidity
bool v146SShowSignalZones
bool v146SSupplyActive
float v146SSupplyBottom
float v146SSupplyTop
int volBear
int volBull
int volSpikeLen
float volSpikeMult
float wyckMajorAtrMult
int wyckMajorDebounceBars
int wyckMajorVolLen
float wyckMajorVolMult
bool wyckoffEnable
bool wyckoffMajorOnly
int wyckoffMinMomConf
bool wyckoffRequireCHoCH
export type LegacyLiquidityResult
bool bslReclaim
bool bslSweep
bool canSpringBuyRaw
bool canSpringSellRaw
float eqhLvl
float eqlLvl
bool isSOS
bool isSOW
int liqBearPts
int liqBullPts
int sosPts
int sowPts
bool springBear
bool springBull
bool springPrimaryBuyRaw
bool springPrimarySellRaw
bool sslReclaim
bool sslSweep
float v14291Visual17Arg00
color v14291Visual17Arg02
float v14291Visual18Arg00
color v14291Visual18Arg02
bool v14291Visual19Arg00
color v14291Visual19Arg04
bool v14291Visual20Arg00
color v14291Visual20Arg04
bool v14291Visual21Arg00
color v14291Visual21Arg04
bool v14291Visual22Arg00
color v14291Visual22Arg04
compat_Liquidity_f_best_cluster(array<float> pivs, float tol, int minTouches) =>
float best = na
int bestHits = 0
int n = array.size(pivs)
if n == 0
best
else
for i = 0 to n - 1
float cur = array.get(pivs, i)
int hits = 0
for j = 0 to n - 1
float v = array.get(pivs, j)
if math.abs(cur - v) <= tol
hits += 1
if hits >= minTouches
if hits > bestHits
bestHits := hits
best := cur
else if hits == bestHits and not na(best)
if math.abs(cur - close) < math.abs(best - close)
best := cur
best
//@function v14.31 Liquidity extraction. Call once per chart execution at original evaluation point.
export legacyLiquidity(LegacyLiquidityConfig _cfg) =>
// =============================================================================
// [F0] LIQUIDITY ENGINE — ONE-SHOT EQH/EQL POOLS + WYCKOFF SOS/SOW
// Hour-anchored normalization so behavior is consistent across TFs (1H/4H/1D).
// =============================================================================
// --- Timeframe -> hours
tfSec = timeframe.in_seconds(timeframe.period)
tfHours = math.max(0.001, float(tfSec) / 3600.0)
// --- Convert hour-based windows -> bars (with clamps)
liqLookbackBars = int(math.round(_cfg.liqLookbackH / tfHours))
sweepConfirmBars = int(math.round(_cfg.sweepConfirmH / tfHours))
liqLookbackBars := math.max(20, math.min(240, liqLookbackBars))
sweepConfirmBars := math.max(5, math.min(120, sweepConfirmBars))
// --- Liquidity pivot storage (value + time) using same pivot params as S/R for consistency
var float[] liqHighVals = array.new<float>()
var int[] liqHighTs = array.new<int>()
var float[] liqLowVals = array.new<float>()
var int[] liqLowTs = array.new<int>()
// Capture confirmed pivots (time of pivot bar is time[pivotRight])
if not na(_cfg.pivotH)
array.unshift(liqHighVals, _cfg.pivotH)
array.unshift(liqHighTs, time[_cfg.pivotRight])
if not na(_cfg.pivotL)
array.unshift(liqLowVals, _cfg.pivotL)
array.unshift(liqLowTs, time[_cfg.pivotRight])
// --- Cleanup old pivots by time (lookback in hours)
liqLookbackMs = _cfg.liqLookbackH * 3600000
while array.size(liqHighTs) > 0 and (time - array.get(liqHighTs, array.size(liqHighTs)-1)) > liqLookbackMs
array.pop(liqHighVals)
array.pop(liqHighTs)
while array.size(liqLowTs) > 0 and (time - array.get(liqLowTs, array.size(liqLowTs)-1)) > liqLookbackMs
array.pop(liqLowVals)
array.pop(liqLowTs)
// --- Best-cluster selector (max hits, tie-break = closest to price)
liqTol = ta.atr(14) * _cfg.liqTolMult
int effTouches = _cfg.liqMinTouches
float eqhCandidate = na
float eqlCandidate = na
// Candidate detection uses EQH/EQL clustering with a stateful pool lifecycle.
// each selected pool a lifecycle identity so the same pool cannot print repeatedly.
eqhCandidate := _cfg.enableLiquidity ? compat_Liquidity_f_best_cluster(liqHighVals, liqTol, effTouches) : na
eqlCandidate := _cfg.enableLiquidity ? compat_Liquidity_f_best_cluster(liqLowVals, liqTol, effTouches) : na
if _cfg.enableLiquidity and _cfg.enableRelaxPools
int relaxTouches = math.max(1, effTouches - _cfg.relaxTouchDrop)
float relaxTol = liqTol * _cfg.relaxTolScale
if na(eqhCandidate)
eqhCandidate := compat_Liquidity_f_best_cluster(liqHighVals, relaxTol, relaxTouches)
if na(eqlCandidate)
eqlCandidate := compat_Liquidity_f_best_cluster(liqLowVals, relaxTol, relaxTouches)
var float eqhLvl = na
var float eqlLvl = na
var bool eqhPoolConsumed = false
var bool eqlPoolConsumed = false
var int eqhConsumedPivotTs = na
var int eqlConsumedPivotTs = na
var float eqhConsumedPrice = na
var float eqlConsumedPrice = na
var int eqhConsumedTime = na
var int eqlConsumedTime = na
var int eqhPoolBornTime = na
var int eqlPoolBornTime = na
int newestHighPivotTs = array.size(liqHighTs) > 0 ? array.get(liqHighTs, 0) : na
int newestLowPivotTs = array.size(liqLowTs) > 0 ? array.get(liqLowTs, 0) : na
bool newHighPivotNow = not na(_cfg.pivotH)
bool newLowPivotNow = not na(_cfg.pivotL)
float newPoolTol = ta.atr(14) * _cfg.v146SNewPoolTolAtr
if not _cfg.enableLiquidity
eqhLvl := na
eqlLvl := na
eqhPoolConsumed := false
eqlPoolConsumed := false
eqhConsumedPrice := na
eqlConsumedPrice := na
eqhConsumedTime := na
eqlConsumedTime := na
else
// Expire an unswept pool after the same lookback used to build it.
if not na(eqhPoolBornTime) and time - eqhPoolBornTime > liqLookbackMs
eqhLvl := na
eqhPoolBornTime := na
if not na(eqlPoolBornTime) and time - eqlPoolBornTime > liqLookbackMs
eqlLvl := na
eqlPoolBornTime := na
float consumedPoolTol = ta.atr(14) * math.max(_cfg.v146SNewPoolTolAtr, _cfg.v146LConsumedPoolLockAtr)
bool eqhConsumedRegionLocked = not na(eqhConsumedPrice) and not na(eqhConsumedTime) and (time - eqhConsumedTime <= liqLookbackMs) and not na(eqhCandidate) and math.abs(eqhCandidate - eqhConsumedPrice) <= consumedPoolTol
bool eqlConsumedRegionLocked = not na(eqlConsumedPrice) and not na(eqlConsumedTime) and (time - eqlConsumedTime <= liqLookbackMs) and not na(eqlCandidate) and math.abs(eqlCandidate - eqlConsumedPrice) <= consumedPoolTol
bool canRearmEqh = not _cfg.v146SOneShotLiquidity or not eqhPoolConsumed or ((newHighPivotNow and not na(newestHighPivotTs) and (na(eqhConsumedPivotTs) or newestHighPivotTs > eqhConsumedPivotTs)) and not eqhConsumedRegionLocked)
bool canRearmEql = not _cfg.v146SOneShotLiquidity or not eqlPoolConsumed or ((newLowPivotNow and not na(newestLowPivotTs) and (na(eqlConsumedPivotTs) or newestLowPivotTs > eqlConsumedPivotTs)) and not eqlConsumedRegionLocked)
if na(eqhLvl) and canRearmEqh and not na(eqhCandidate)
eqhLvl := eqhCandidate
eqhPoolBornTime := time
eqhPoolConsumed := false
else if newHighPivotNow and canRearmEqh and not na(eqhCandidate) and not na(eqhLvl) and math.abs(eqhCandidate - eqhLvl) > newPoolTol
eqhLvl := eqhCandidate
eqhPoolBornTime := time
eqhPoolConsumed := false
if na(eqlLvl) and canRearmEql and not na(eqlCandidate)
eqlLvl := eqlCandidate
eqlPoolBornTime := time
eqlPoolConsumed := false
else if newLowPivotNow and canRearmEql and not na(eqlCandidate) and not na(eqlLvl) and math.abs(eqlCandidate - eqlLvl) > newPoolTol
eqlLvl := eqlCandidate
eqlPoolBornTime := time
eqlPoolConsumed := false
// --- Sweep detection: one confirmed event per active pool.
float bslSweepLevelNow = eqhLvl
float sslSweepLevelNow = eqlLvl
penetrateUp = _cfg.useCloseForSweep ? (not na(eqhLvl) and close > eqhLvl) : (not na(eqhLvl) and high > eqhLvl)
penetrateDn = _cfg.useCloseForSweep ? (not na(eqlLvl) and close < eqlLvl) : (not na(eqlLvl) and low < eqlLvl)
bslSweep = barstate.isconfirmed and _cfg.enableLiquidity and not na(eqhLvl) and (not _cfg.v146SOneShotLiquidity or not eqhPoolConsumed) and penetrateUp and close < eqhLvl
sslSweep = barstate.isconfirmed and _cfg.enableLiquidity and not na(eqlLvl) and (not _cfg.v146SOneShotLiquidity or not eqlPoolConsumed) and penetrateDn and close > eqlLvl
// --- Pending reclaim windows use the exact frozen swept level.
var int pendSslBi = na
var float pendEql = na
var int pendBslBi = na
var float pendEqh = na
if sslSweep
pendSslBi := bar_index
pendEql := sslSweepLevelNow
if _cfg.v146SOneShotLiquidity
eqlPoolConsumed := true
eqlConsumedPivotTs := newestLowPivotTs
eqlConsumedPrice := sslSweepLevelNow
eqlConsumedTime := time
eqlLvl := na
eqlPoolBornTime := na
if bslSweep
pendBslBi := bar_index
pendEqh := bslSweepLevelNow
if _cfg.v146SOneShotLiquidity
eqhPoolConsumed := true
eqhConsumedPivotTs := newestHighPivotTs
eqhConsumedPrice := bslSweepLevelNow
eqhConsumedTime := time
eqhLvl := na
eqhPoolBornTime := na
sslReclaim = _cfg.enableLiquidity and not na(pendSslBi) and (bar_index - pendSslBi) <= sweepConfirmBars and not na(pendEql) and close > pendEql
bslReclaim = _cfg.enableLiquidity and not na(pendBslBi) and (bar_index - pendBslBi) <= sweepConfirmBars and not na(pendEqh) and close < pendEqh
if not na(pendSslBi) and ((bar_index - pendSslBi) > sweepConfirmBars or sslReclaim)
pendSslBi := na
pendEql := na
if not na(pendBslBi) and ((bar_index - pendBslBi) > sweepConfirmBars or bslReclaim)
pendBslBi := na
pendEqh := na
// --- Strong sweep override (prevents missed reversals on fast springs / upthrusts)
volSma_spike = ta.sma(volume, _cfg.volSpikeLen)
isVolSpike = volume > volSma_spike * _cfg.volSpikeMult
wickBullOK = _cfg.candleRange > 0 ? (_cfg.lowerWick / _cfg.candleRange) >= _cfg.sweepWickRatio : false
wickBearOK = _cfg.candleRange > 0 ? (_cfg.upperWick / _cfg.candleRange) >= _cfg.sweepWickRatio : false
strongBull = _cfg.enableStrongSweepOverride and isVolSpike and wickBullOK
strongBear = _cfg.enableStrongSweepOverride and isVolSpike and wickBearOK
// --- Spring / Upthrust override (support-based; does NOT require EQH/EQL pools)
volSma_spring = ta.sma(volume, _cfg.springVolLen)
isVolSpring = volume > volSma_spring * _cfg.springVolMult
springBullWickOK = _cfg.candleRange > 0 ? (_cfg.lowerWick / _cfg.candleRange) >= _cfg.springWickRatio : false
springBearWickOK = _cfg.candleRange > 0 ? (_cfg.upperWick / _cfg.candleRange) >= _cfg.springWickRatio : false
springTol = ta.atr(14) * _cfg.srRetestTolMult
springBullSR = (not na(_cfg.support)) and (low < (_cfg.support - springTol)) and (close > _cfg.support)
springBearSR = (not na(_cfg.resistance)) and (high > (_cfg.resistance + springTol)) and (close < _cfg.resistance)
springBull = _cfg.enableSpringOverride and isVolSpring and springBullWickOK and (not _cfg.springUseSR or springBullSR)
springBear = _cfg.enableSpringOverride and isVolSpring and springBearWickOK and (not _cfg.springUseSR or springBearSR)
// --- Liquidity score contribution (momentum-coupled)
liqBullPts = _cfg.enableLiquidity and (sslReclaim or springBull) and (((_cfg.srMomBullCnt >= _cfg.liqMinMomConf) or strongBull) or springBull) ? _cfg.liqScorePts : 0
liqBearPts = _cfg.enableLiquidity and (bslReclaim or springBear) and (((_cfg.srMomBearCnt >= _cfg.liqMinMomConf) or strongBear) or springBear) ? _cfg.liqScorePts : 0
// --- Wyckoff SOS/SOW
wyckMomBullOK = (_cfg.srMomBullCnt >= _cfg.wyckoffMinMomConf) or strongBull or springBull
wyckMomBearOK = (_cfg.srMomBearCnt >= _cfg.wyckoffMinMomConf) or strongBear or springBear
wyckVolBullOK = (_cfg.obvBull > 0) or (_cfg.volBull > 0)
wyckVolBearOK = (_cfg.obvBear > 0) or (_cfg.volBear > 0)
var int _lastSOSBar = na
var int _lastSOWBar = na
// Major structure break filter (reduces noisy SOS/SOW spam):
// - Require close beyond current S/R by ATR buffer
// - Require volume > SMA * mult
// - Debounce repeated prints
_wyAtrBuf = ta.atr(14) * _cfg.wyckMajorAtrMult
_wyVolSma = ta.sma(volume, _cfg.wyckMajorVolLen)
_wyVolOK = volume > _wyVolSma * _cfg.wyckMajorVolMult
_wyMajorSOS = (not na(_cfg.resistance)) and close > (_cfg.resistance + _wyAtrBuf) and _wyVolOK
_wyMajorSOW = (not na(_cfg.support)) and close < (_cfg.support - _wyAtrBuf) and _wyVolOK
_canSOSMajor = na(_lastSOSBar) or (bar_index - _lastSOSBar > _cfg.wyckMajorDebounceBars)
_canSOWMajor = na(_lastSOWBar) or (bar_index - _lastSOWBar > _cfg.wyckMajorDebounceBars)
isSOS = _cfg.wyckoffEnable and _cfg.enableLiquidity and (sslReclaim or springBull) and wyckMomBullOK and wyckVolBullOK and (not _cfg.wyckoffRequireCHoCH or _cfg.smsChochUp) and (not _cfg.wyckoffMajorOnly or (_wyMajorSOS and _canSOSMajor))
isSOW = _cfg.wyckoffEnable and _cfg.enableLiquidity and (bslReclaim or springBear) and wyckMomBearOK and wyckVolBearOK and (not _cfg.wyckoffRequireCHoCH or _cfg.smsChochDn) and (not _cfg.wyckoffMajorOnly or (_wyMajorSOW and _canSOWMajor))
if isSOS and _cfg.wyckoffMajorOnly
_lastSOSBar := bar_index
if isSOW and _cfg.wyckoffMajorOnly
_lastSOWBar := bar_index
sosPts = _cfg.wyckoffEnable and isSOS ? _cfg.sosScorePts : 0
sowPts = _cfg.wyckoffEnable and isSOW ? _cfg.sowScorePts : 0
// Primary Spring/Upthrust markers remain separate from the main BUY/SELL state engine.
// volCheck is computed later in [G]; this block builds the raw Spring/Upthrust conditions.
springPrimaryBuyRaw = _cfg.enableLiquidity and _cfg.enableSpringPrimary and springBull and (_cfg.srMomBullCnt >= _cfg.springPrimaryMinMomConf) and (not _cfg.springPrimaryRequireCHoCH or _cfg.smsChochUp)
springPrimarySellRaw = _cfg.enableLiquidity and _cfg.enableSpringPrimary and springBear and (_cfg.srMomBearCnt >= _cfg.springPrimaryMinMomConf) and (not _cfg.springPrimaryRequireCHoCH or _cfg.smsChochDn)
canSpringBuyRaw = na(_cfg.lastSpringBuyBar) or (bar_index - _cfg.lastSpringBuyBar > _cfg.springPrimaryDebounceBars)
canSpringSellRaw = na(_cfg.lastSpringSellBar) or (bar_index - _cfg.lastSpringSellBar > _cfg.springPrimaryDebounceBars)
// --- Liquidity line visuals (use plot to avoid line-spam)
bool v146SEqhMerged = _cfg.v146SShowSignalZones and _cfg.v146SSupplyActive and not na(eqhLvl) and not na(_cfg.v146SSupplyTop) and not na(_cfg.v146SSupplyBottom) and eqhLvl >= _cfg.v146SSupplyBottom - ta.atr(14) * _cfg.v146SConfluenceTolAtr and eqhLvl <= _cfg.v146SSupplyTop + ta.atr(14) * _cfg.v146SConfluenceTolAtr
bool v146SEqlMerged = _cfg.v146SShowSignalZones and _cfg.v146SDemandActive and not na(eqlLvl) and not na(_cfg.v146SDemandTop) and not na(_cfg.v146SDemandBottom) and eqlLvl >= _cfg.v146SDemandBottom - ta.atr(14) * _cfg.v146SConfluenceTolAtr and eqlLvl <= _cfg.v146SDemandTop + ta.atr(14) * _cfg.v146SConfluenceTolAtr
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual17Arg00 = _cfg.showLiquidityLines and _cfg.v1429ViewContext and not v146SEqhMerged ? eqhLvl : na
color v14291Visual17Arg02 = _cfg.colEQH
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
float v14291Visual18Arg00 = _cfg.showLiquidityLines and _cfg.v1429ViewContext and not v146SEqlMerged ? eqlLvl : na
color v14291Visual18Arg02 = _cfg.colEQL
// --- Sweep/Reclaim markers
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual19Arg00 = _cfg.showSweepMarkers and _cfg.v1429ViewContext and bslSweep
color v14291Visual19Arg04 = _cfg.colSweepBear
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual20Arg00 = _cfg.showSweepMarkers and _cfg.v1429ViewContext and sslSweep
color v14291Visual20Arg04 = _cfg.colSweepBull
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual21Arg00 = _cfg.showSweepMarkers and _cfg.v1429ViewFullStructure and _cfg.v146SDetailed and (bslReclaim and not bslSweep)
color v14291Visual21Arg04 = _cfg.colSweepBear
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual22Arg00 = _cfg.showSweepMarkers and _cfg.v1429ViewFullStructure and _cfg.v146SDetailed and (sslReclaim and not sslSweep)
color v14291Visual22Arg04 = _cfg.colSweepBull
// --- SOS/SOW labels (time-anchored)
if _cfg.showSOSLabels and _cfg.v1429ViewFullStructure
if isSOS
label.new(time, low, "SOS", xloc=xloc.bar_time, style=label.style_label_up, textcolor=color.white, color=_cfg.colSOS, size=size.small)
if isSOW
label.new(time, high, "SOW", xloc=xloc.bar_time, style=label.style_label_down, textcolor=color.white, color=_cfg.colSOW, size=size.small)
LegacyLiquidityResult.new(bslReclaim, bslSweep, canSpringBuyRaw, canSpringSellRaw, eqhLvl, eqlLvl, isSOS, isSOW, liqBearPts, liqBullPts, sosPts, sowPts, springBear, springBull, springPrimaryBuyRaw, springPrimarySellRaw, sslReclaim, sslSweep, v14291Visual17Arg00, v14291Visual17Arg02, v14291Visual18Arg00, v14291Visual18Arg02, v14291Visual19Arg00, v14291Visual19Arg04, v14291Visual20Arg00, v14291Visual20Arg04, v14291Visual21Arg00, v14291Visual21Arg04, v14291Visual22Arg00, v14291Visual22Arg04)
// === TRAP COMPATIBILITY SERVICE ===
export type LegacyTrapConfig
bool srBreakDnEvent
float srBreakDnLevelNow
bool srBreakUpEvent
float srBreakUpLevelNow
bool srRetestBear
bool srRetestBull
bool tlBreakDnFailedNow
bool tlBreakUpFailedNow
float trapFailBufferAtr
bool trapRequireVolume
float trap_volume_ratio
int trap_window
bool v1429ViewDetailed
int volSmaLen
export type LegacyTrapResult
bool bearTrap
bool bullTrap
bool v14291Visual23Arg00
color v14291Visual23Arg03
bool v14291Visual24Arg00
color v14291Visual24Arg03
//@function v14.31 Trap extraction. Call once per chart execution at original evaluation point.
export legacyTrap(LegacyTrapConfig _cfg) =>
volSMA_trap = ta.sma(volume, _cfg.volSmaLen)
float trapFailBuffer = ta.atr(14) * _cfg.trapFailBufferAtr
// Freeze each major S/R break. A single successful retest, failure, opposite break,
// or expiry consumes the event so the same breakout cannot print repeated traps.
var bool srUpTrapActive = false
var float srUpTrapLevel = na
var int srUpTrapBar = na
var bool srUpTrapVolOK = false
var bool srDnTrapActive = false
var float srDnTrapLevel = na
var int srDnTrapBar = na
var bool srDnTrapVolOK = false
if _cfg.srBreakUpEvent
srUpTrapActive := true
srUpTrapLevel := _cfg.srBreakUpLevelNow
srUpTrapBar := bar_index
srUpTrapVolOK := volume >= volSMA_trap * _cfg.trap_volume_ratio
if _cfg.srBreakDnEvent
srDnTrapActive := true
srDnTrapLevel := _cfg.srBreakDnLevelNow
srDnTrapBar := bar_index
srDnTrapVolOK := volume >= volSMA_trap * _cfg.trap_volume_ratio
bool srBreakUpFailedNow = false
bool srBreakDnFailedNow = false
if barstate.isconfirmed
if srUpTrapActive and bar_index > nz(srUpTrapBar, bar_index)
if _cfg.srRetestBull
srUpTrapActive := false
else if close < srUpTrapLevel - trapFailBuffer and bar_index - srUpTrapBar <= _cfg.trap_window
srBreakUpFailedNow := true
srUpTrapActive := false
else if bar_index - srUpTrapBar > _cfg.trap_window or _cfg.srBreakDnEvent
srUpTrapActive := false
if srDnTrapActive and bar_index > nz(srDnTrapBar, bar_index)
if _cfg.srRetestBear
srDnTrapActive := false
else if close > srDnTrapLevel + trapFailBuffer and bar_index - srDnTrapBar <= _cfg.trap_window
srBreakDnFailedNow := true
srDnTrapActive := false
else if bar_index - srDnTrapBar > _cfg.trap_window or _cfg.srBreakUpEvent
srDnTrapActive := false
bool trapVolOK = not _cfg.trapRequireVolume or volume >= volSMA_trap * _cfg.trap_volume_ratio
// Trendline failures already come from a one-shot dominant boundary. S/R failures
// additionally remember whether the original break itself had strong volume.
bullTrap = (_cfg.tlBreakUpFailedNow and trapVolOK) or (srBreakUpFailedNow and (trapVolOK or srUpTrapVolOK))
bearTrap = (_cfg.tlBreakDnFailedNow and trapVolOK) or (srBreakDnFailedNow and (trapVolOK or srDnTrapVolOK))
// Trap presentation hierarchy:
// - Classic / Clean / Standard: compact single-line Bull Trap / Bear Trap labels.
// - Detailed: full-size Bull Trap / Bear Trap labels.
// - The original cross anchor is restored for all views using the same two existing plotshape slots.
// Trap detection itself is unchanged and retains zero BUY/SELL authority.
if bullTrap
if _cfg.v1429ViewDetailed
label.new(bar_index, high, "Bull Trap", color=color.orange, style=label.style_label_down, textcolor=color.white)
else
label.new(bar_index, high, "Bull Trap", color=color.new(color.orange, 5), style=label.style_label_down, textcolor=color.white, size=size.small)
if bearTrap
if _cfg.v1429ViewDetailed
label.new(bar_index, low, "Bear Trap", color=color.rgb(136, 210, 217), style=label.style_label_up, textcolor=color.white)
else
label.new(bar_index, low, "Bear Trap", color=color.new(color.rgb(136, 210, 217), 5), style=label.style_label_up, textcolor=color.white, size=size.small)
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual23Arg00 = bullTrap
color v14291Visual23Arg03 = color.orange
// 14.29.1 capture: preserve original visual evaluation before reserved alert plots.
bool v14291Visual24Arg00 = bearTrap
color v14291Visual24Arg03 = color.rgb(42, 201, 225)
LegacyTrapResult.new(bearTrap, bullTrap, v14291Visual23Arg00, v14291Visual23Arg03, v14291Visual24Arg00, v14291Visual24Arg03)
// === TARGETS COMPATIBILITY SERVICE ===
export type LegacyTargetsConfig
int v146TargetLookbackBars
int v146TargetMaxPivots
int v146TargetPivotBars
export type LegacyTargetsResult
array<int> v146TargetHighBars
array<float> v146TargetHighVals
array<int> v146TargetLowBars
array<float> v146TargetLowVals
export legacyTwoTargets(array<float> vals, array<int> bars, float threshold, int minTouches, int minGapBars, int dir, float entry, float minDistance) =>
float out1 = na
float out2 = na
float bestD1 = 1.0e20
float bestD2 = 1.0e20
float[] zones = array.new<float>()
int n = array.size(vals)
if n > 0 and threshold > 0
for i = 0 to n - 1
float cur = array.get(vals, i)
bool sideOK = dir == 1 ? cur > entry + minDistance : cur < entry - minDistance
if sideOK
int hits = 0
float sumV = 0.0
int lastAcceptedB = na
for j = 0 to n - 1
float v = array.get(vals, j)
int b = array.get(bars, j)
if math.abs(v - cur) <= threshold and (na(lastAcceptedB) or math.abs(b - lastAcceptedB) >= minGapBars)
hits += 1
sumV += v
lastAcceptedB := b
if hits >= minTouches
float zone = sumV / hits
float dist = dir == 1 ? zone - entry : entry - zone
if dist >= minDistance
bool distinct = true
int zn = array.size(zones)
if zn > 0
for k = 0 to zn - 1
if math.abs(zone - array.get(zones, k)) <= threshold * 0.80
distinct := false
if distinct
array.push(zones, zone)
int zn2 = array.size(zones)
if zn2 > 0
for k = 0 to zn2 - 1
float z = array.get(zones, k)
float d = dir == 1 ? z - entry : entry - z
if d < bestD1
bestD2 := bestD1
out2 := out1
bestD1 := d
out1 := z
else if d < bestD2
bestD2 := d
out2 := z
[out1, out2]
//@function v14.31 Targets extraction. Call once per chart execution at original evaluation point.
export legacyTargets(LegacyTargetsConfig _cfg) =>
// --- Structure-aware target map and signal-panel state ---
// Information only. Nothing in this section feeds the primary BUY/SELL state.
// Targets use confirmed multi-touch swing clusters plus causal trend/turn structure in the signal direction.
// If valid structure is unavailable, universal R-multiple fallbacks are used.
var float[] v146TargetHighVals = array.new<float>()
var int[] v146TargetHighBars = array.new<int>()
var float[] v146TargetLowVals = array.new<float>()
var int[] v146TargetLowBars = array.new<int>()
float v146TargetPH = ta.pivothigh(high, _cfg.v146TargetPivotBars, _cfg.v146TargetPivotBars)
float v146TargetPL = ta.pivotlow(low, _cfg.v146TargetPivotBars, _cfg.v146TargetPivotBars)
if not na(v146TargetPH)
array.unshift(v146TargetHighVals, v146TargetPH)
array.unshift(v146TargetHighBars, bar_index - _cfg.v146TargetPivotBars)
if not na(v146TargetPL)
array.unshift(v146TargetLowVals, v146TargetPL)
array.unshift(v146TargetLowBars, bar_index - _cfg.v146TargetPivotBars)
while array.size(v146TargetHighBars) > 0 and (bar_index - array.get(v146TargetHighBars, array.size(v146TargetHighBars) - 1) > _cfg.v146TargetLookbackBars or array.size(v146TargetHighBars) > _cfg.v146TargetMaxPivots)
array.pop(v146TargetHighVals)
array.pop(v146TargetHighBars)
while array.size(v146TargetLowBars) > 0 and (bar_index - array.get(v146TargetLowBars, array.size(v146TargetLowBars) - 1) > _cfg.v146TargetLookbackBars or array.size(v146TargetLowBars) > _cfg.v146TargetMaxPivots)
array.pop(v146TargetLowVals)
array.pop(v146TargetLowBars)
LegacyTargetsResult.new(v146TargetHighBars, v146TargetHighVals, v146TargetLowBars, v146TargetLowVals)
// === FRESH COMPATIBILITY SERVICE ===
export type LegacyFreshConfig
float clusterDistance
color colResBorder
color colSupBorder
color colTLRes
color colTLSup
float eqhLvl
float eqlLvl
float res_tl_y
float resistance
float sup_tl_y
float support
line tlFlipResistanceLine
line tlFlipSupportLine
float v146Atr
bool v146LMergeStructureZones
bool v146PrimaryBuy
bool v146PrimarySell
float v146SBearCampaignHigh
int v146SBearCampaignHighTime
bool v146SBearCampaignTracking
float v146SBullCampaignLow
int v146SBullCampaignLowTime
bool v146SBullCampaignTracking
float v146SConfluenceTolAtr
bool v146SDemandActive
int v146SDemandBornBar
float v146SDemandBottom
box v146SDemandBox
int v146SDemandLeftTime
float v146SDemandTop
bool v146SShowSignalZones
float v146SSignalZoneInvalidAtr
int v146SSignalZoneMaxBars
float v146SSignalZoneWidthAtr
bool v146SSupplyActive
int v146SSupplyBornBar
float v146SSupplyBottom
box v146SSupplyBox
int v146SSupplyLeftTime
float v146SSupplyTop
//@function v14.31 Fresh extraction. Call once per chart execution at original evaluation point.
export legacyFresh(LegacyFreshConfig _cfg) =>
// --- Signal-derived fresh supply / demand ---
// These zones do not authorize BUY/SELL. They simply preserve the actual reversal
// origin after the primary signal is confirmed, so fresh structure appears without
// waiting several extra pivot-right bars.
if barstate.isconfirmed
float _sigZoneInvalid = _cfg.v146Atr * _cfg.v146SSignalZoneInvalidAtr
if _cfg.v146SShowSignalZones and _cfg.v146PrimaryBuy and not na(_cfg.v146SBullCampaignLow)
_cfg.v146SDemandBottom := _cfg.v146SBullCampaignLow
_cfg.v146SDemandTop := _cfg.v146SBullCampaignLow + _cfg.v146Atr * _cfg.v146SSignalZoneWidthAtr
_cfg.v146SDemandLeftTime := nz(_cfg.v146SBullCampaignLowTime, time)
_cfg.v146SDemandBornBar := bar_index
_cfg.v146SDemandActive := true
if not na(_cfg.v146SDemandBox)
box.delete(_cfg.v146SDemandBox)
bool _demandConfluence = (not na(_cfg.support) and math.abs(_cfg.support - (_cfg.v146SDemandTop + _cfg.v146SDemandBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr) or (not na(_cfg.sup_tl_y) and math.abs(_cfg.sup_tl_y - (_cfg.v146SDemandTop + _cfg.v146SDemandBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr) or (not na(_cfg.eqlLvl) and math.abs(_cfg.eqlLvl - (_cfg.v146SDemandTop + _cfg.v146SDemandBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr)
_cfg.v146SDemandBox := box.new(left=_cfg.v146SDemandLeftTime, top=_cfg.v146SDemandTop, right=time, bottom=_cfg.v146SDemandBottom, xloc=xloc.bar_time, border_color=_cfg.colSupBorder, bgcolor=color.new(_cfg.colSupBorder, 88), border_width=_demandConfluence ? 3 : 2)
_cfg.v146SBullCampaignTracking := false
if _cfg.v146SShowSignalZones and _cfg.v146PrimarySell and not na(_cfg.v146SBearCampaignHigh)
_cfg.v146SSupplyTop := _cfg.v146SBearCampaignHigh
_cfg.v146SSupplyBottom := _cfg.v146SBearCampaignHigh - _cfg.v146Atr * _cfg.v146SSignalZoneWidthAtr
_cfg.v146SSupplyLeftTime := nz(_cfg.v146SBearCampaignHighTime, time)
_cfg.v146SSupplyBornBar := bar_index
_cfg.v146SSupplyActive := true
if not na(_cfg.v146SSupplyBox)
box.delete(_cfg.v146SSupplyBox)
bool _supplyConfluence = (not na(_cfg.resistance) and math.abs(_cfg.resistance - (_cfg.v146SSupplyTop + _cfg.v146SSupplyBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr) or (not na(_cfg.res_tl_y) and math.abs(_cfg.res_tl_y - (_cfg.v146SSupplyTop + _cfg.v146SSupplyBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr) or (not na(_cfg.eqhLvl) and math.abs(_cfg.eqhLvl - (_cfg.v146SSupplyTop + _cfg.v146SSupplyBottom) * 0.5) <= _cfg.v146Atr * _cfg.v146SConfluenceTolAtr)
_cfg.v146SSupplyBox := box.new(left=_cfg.v146SSupplyLeftTime, top=_cfg.v146SSupplyTop, right=time, bottom=_cfg.v146SSupplyBottom, xloc=xloc.bar_time, border_color=_cfg.colResBorder, bgcolor=color.new(_cfg.colResBorder, 88), border_width=_supplyConfluence ? 3 : 2)
_cfg.v146SBearCampaignTracking := false
// Confirmed invalidation/age retirement. A fresh zone is context, not a permanent wall.
if _cfg.v146SDemandActive and (close < _cfg.v146SDemandBottom - _sigZoneInvalid or bar_index - nz(_cfg.v146SDemandBornBar, bar_index) > _cfg.v146SSignalZoneMaxBars)
_cfg.v146SDemandActive := false
if not na(_cfg.v146SDemandBox)
box.delete(_cfg.v146SDemandBox)
_cfg.v146SDemandBox := na
if _cfg.v146SSupplyActive and (close > _cfg.v146SSupplyTop + _sigZoneInvalid or bar_index - nz(_cfg.v146SSupplyBornBar, bar_index) > _cfg.v146SSignalZoneMaxBars)
_cfg.v146SSupplyActive := false
if not na(_cfg.v146SSupplyBox)
box.delete(_cfg.v146SSupplyBox)
_cfg.v146SSupplyBox := na
// Keep active fresh zones extended to the current bar. Structure merging can absorb nearby
// ranked S/R and flipped trendline structure into the same visible zone. The base
// signal-origin boundaries remain unchanged for causal invalidation logic.
if _cfg.v146SShowSignalZones and _cfg.v146SDemandActive and not na(_cfg.v146SDemandBox)
float _dTop = _cfg.v146SDemandTop
float _dBot = _cfg.v146SDemandBottom
bool _dMerged = false
float _dMid = (_cfg.v146SDemandTop + _cfg.v146SDemandBottom) * 0.5
float _dTol = _cfg.v146Atr * _cfg.v146SConfluenceTolAtr
if _cfg.v146LMergeStructureZones and not na(_cfg.support) and math.abs(_cfg.support - _dMid) <= _dTol
_dTop := math.max(_dTop, _cfg.support + _cfg.clusterDistance * 0.5)
_dBot := math.min(_dBot, _cfg.support - _cfg.clusterDistance * 0.5)
_dMerged := true
if _cfg.v146LMergeStructureZones and not na(_cfg.tlFlipSupportLine)
float _flipDY = lineYAtTime(_cfg.tlFlipSupportLine, time)
if math.abs(_flipDY - _dMid) <= _dTol
_dTop := math.max(_dTop, _flipDY + _cfg.clusterDistance * 0.20)
_dBot := math.min(_dBot, _flipDY - _cfg.clusterDistance * 0.20)
_dMerged := true
line.set_color(_cfg.tlFlipSupportLine, color.new(_cfg.colTLSup, 100))
else
line.set_color(_cfg.tlFlipSupportLine, color.new(_cfg.colTLSup, 35))
box.set_top(_cfg.v146SDemandBox, _dTop)
box.set_bottom(_cfg.v146SDemandBox, _dBot)
box.set_border_width(_cfg.v146SDemandBox, _dMerged ? 3 : 2)
box.set_right(_cfg.v146SDemandBox, time)
if _cfg.v146SShowSignalZones and _cfg.v146SSupplyActive and not na(_cfg.v146SSupplyBox)
float _sTop = _cfg.v146SSupplyTop
float _sBot = _cfg.v146SSupplyBottom
bool _sMerged = false
float _sMid = (_cfg.v146SSupplyTop + _cfg.v146SSupplyBottom) * 0.5
float _sTol = _cfg.v146Atr * _cfg.v146SConfluenceTolAtr
if _cfg.v146LMergeStructureZones and not na(_cfg.resistance) and math.abs(_cfg.resistance - _sMid) <= _sTol
_sTop := math.max(_sTop, _cfg.resistance + _cfg.clusterDistance * 0.5)
_sBot := math.min(_sBot, _cfg.resistance - _cfg.clusterDistance * 0.5)
_sMerged := true
if _cfg.v146LMergeStructureZones and not na(_cfg.tlFlipResistanceLine)
float _flipSY = lineYAtTime(_cfg.tlFlipResistanceLine, time)
if math.abs(_flipSY - _sMid) <= _sTol
_sTop := math.max(_sTop, _flipSY + _cfg.clusterDistance * 0.20)
_sBot := math.min(_sBot, _flipSY - _cfg.clusterDistance * 0.20)
_sMerged := true
line.set_color(_cfg.tlFlipResistanceLine, color.new(_cfg.colTLRes, 100))
else
line.set_color(_cfg.tlFlipResistanceLine, color.new(_cfg.colTLRes, 35))
box.set_top(_cfg.v146SSupplyBox, _sTop)
box.set_bottom(_cfg.v146SSupplyBox, _sBot)
box.set_border_width(_cfg.v146SSupplyBox, _sMerged ? 3 : 2)
box.set_right(_cfg.v146SSupplyBox, time)
// If a flipped line was temporarily hidden inside a merged fresh zone and that
// zone later disappears, restore the line's normal role color.
if not _cfg.v146SDemandActive and not na(_cfg.tlFlipSupportLine)
line.set_color(_cfg.tlFlipSupportLine, color.new(_cfg.colTLSup, 35))
if not _cfg.v146SSupplyActive and not na(_cfg.tlFlipResistanceLine)
line.set_color(_cfg.tlFlipResistanceLine, color.new(_cfg.colTLRes, 35))
if not _cfg.v146SShowSignalZones
if not na(_cfg.v146SDemandBox)
box.delete(_cfg.v146SDemandBox)
if not na(_cfg.v146SSupplyBox)
box.delete(_cfg.v146SSupplyBox)
_cfg.v146SDemandBox := na
_cfg.v146SSupplyBox := na
_cfg.v146SDemandActive := false
_cfg.v146SSupplyActive := false
_cfg
// ============================================================================
// ADVANCED ENGINE v1.0: source-context computation only. No request or drawing.
// Time-based fit coordinates match displayed geometry, including session gaps.
// Snapshot fields are scalar-only UDTs; fresh copies are returned on every call.
// ============================================================================
export type Level
int id = 0
int revision = 0
int origin = na
int known = na
int effective = na
float lower = na
float upper = na
int role = 0
int touches = 0
int flips = 0
int state = 0
float quality = 0.0
int spanBars = 0
export type Trend
string id = ""
int x1 = na
int x2 = na
float y1 = na
float y2 = na
int known = na
int role = 0
int touches = 0
int violations = 0
int state = 0
int breakAt = na
int breakDirection = 0
float quality = 0.0
export type Channel
int id = 0
int x1 = na
int x2 = na
float y1 = na
float y2 = na
float sigma = na
float r2 = na
int count = 0
int known = na
int state = 0
int breakDirection = 0
export type Snapshot
string ticker = ""
string tf = ""
int opened = na
int closed = na
int index = 0
float atr = na
bool ready = false
Level s1 = na
Level s2 = na
Level s3 = na
Level r1 = na
Level r2 = na
Level r3 = na
Trend supportLine = na
Trend resistanceLine = na
Trend developingSupport = na
Trend developingResistance = na
Channel rolling = na
Channel frozen = na
float rangeMid = na
bool rangeValid = false
float donHigh = na
float donLow = na
int zoneBreak = 0
int zoneRetest = 0
int zoneFailed = 0
int trendBreak = 0
int trendRetest = 0
int trendFailed = 0
int channelBreak = 0
int evictedId = 0
string evictionReason = ""
int storedZones = 0
type StoredZone
int id
int origin
int known
int bornIndex
float lower
float upper
int role
int touches = 1
int lastTouchIndex = 0
int lastTouchTime = 0
bool armed = false
int revision = 1
int flips = 0
int state = 0
int beyond = 0
int acceptedAt = na
int acceptedIndex = na
bool retested = false
int effective = na
type PivotPoint
float value
int stamp
int idx
export type Events
bool rejectionBuy = false
bool rejectionSell = false
bool confirmBuy = false
bool confirmSell = false
bool breachUp = false
bool breachDown = false
bool lineBreakUp = false
bool lineBreakDown = false
bool channelUp = false
bool channelDown = false
int zoneId = 0
int zoneRevision = 0
float boundary = na
float breachedResistance = na
float breachedSupport = na
float invalidation = na
string eventId = ""
export type Renderer
array<box> zones
array<line> lines
array<label> labels
export newRenderer() =>
Renderer.new(array.new<box>(6), array.new<line>(10), array.new<label>(10))
export primaryTF(simple string chartTf) =>
float sec = timeframe.in_seconds(chartTf)
sec <= 1800 ? "60" : sec <= 3600 ? "240" : sec <= 21600 ? "1D" : sec <= 86400 ? "1W" : sec <= 604800 ? "1M" : sec <= 2678400 ? "3M" : "12M"
export fartherTF(simple string chartTf) =>
float sec = timeframe.in_seconds(chartTf)
sec <= 1800 ? "240" : sec <= 3600 ? "1D" : sec <= 21600 ? "1W" : sec <= 86400 ? "1M" : sec <= 604800 ? "3M" : "12M"
f_zoneQuality(StoredZone z) =>
float span = math.max(0, z.lastTouchIndex - z.bornIndex)
// Ranking, NOT an estimated trade probability. Repeated breaks reduce quality.
math.min(100.0, 20.0 + math.min(z.touches, 6) * 9.0 + math.min(span, 400) * 0.045 + (z.retested ? 8.0 : 0.0) - math.max(0, z.flips - 1) * 8.0)
f_levelCopy(StoredZone z) =>
Level.new(z.id, z.revision, z.origin, z.known, z.effective, z.lower, z.upper, z.role, z.touches, z.flips, z.state, f_zoneQuality(z), math.max(0, z.lastTouchIndex - z.bornIndex))
f_blankLevel() => Level.new()
f_blankTrend() => Trend.new()
f_blankChannel() => Channel.new()
f_trendY(Trend tr, int stamp) =>
not na(tr) and tr.id != "" and tr.x2 > tr.x1 ? tr.y1 + (tr.y2 - tr.y1) * (stamp - tr.x1) / float(tr.x2 - tr.x1) : na
f_channelY(Channel ch, int stamp) =>
not na(ch) and ch.count >= 2 and ch.x2 > ch.x1 ? ch.y1 + (ch.y2 - ch.y1) * (stamp - ch.x1) / float(ch.x2 - ch.x1) : na
export trendValue(Trend tr, int stamp) => f_trendY(tr, stamp)
export channelValue(Channel ch, int stamp) => f_channelY(ch, stamp)
f_addPivot(array<PivotPoint> ps, float value, int stamp, int idx) =>
array.unshift(ps, PivotPoint.new(value, stamp, idx))
if array.size(ps) > 18
array.pop(ps)
array.size(ps)
f_addZone(array<StoredZone> zs, float price, int role, int stamp, int idx, float atr, int gap, int capacity) =>
float half = math.max(syminfo.mintick * 2, atr * 0.25)
int matched = -1
float best = 1.0e20
if array.size(zs) > 0
for j = 0 to array.size(zs) - 1
StoredZone z = array.get(zs, j)
float mid = (z.lower + z.upper) * 0.5
float dist = math.abs(price - mid)
if z.state != 5 and dist <= math.max(half * 2, (z.upper - z.lower) * 0.5) and dist < best
matched := j
best := dist
int evicted = 0
if matched >= 0
StoredZone z = array.get(zs, matched)
// Already-observed candle touches and subsequently confirmed pivots must not double-count.
if idx - z.lastTouchIndex >= gap
z.touches += 1
z.lastTouchIndex := idx
z.lastTouchTime := stamp
// Geometry remains frozen. New evidence updates quality, not historical boundaries.
else
if array.size(zs) >= capacity
int worst = 0
float weakest = 1.0e20
for j = 0 to array.size(zs) - 1
StoredZone z = array.get(zs, j)
float rank = f_zoneQuality(z) - math.max(0, bar_index - z.lastTouchIndex) * 0.035 - (z.state == 5 ? 1000 : 0)
if rank < weakest
worst := j
weakest := rank
StoredZone removed = array.remove(zs, worst)
evicted := removed.id
StoredZone fresh = StoredZone.new(role == 1 ? stamp : -stamp, stamp, time_close, bar_index, price - half, price + half, role)
fresh.lastTouchIndex := idx
fresh.lastTouchTime := stamp
fresh.effective := time_close
array.push(zs, fresh)
evicted
f_bestLevels(array<StoredZone> zs, int role, int minimum, float atr) =>
Level one = f_blankLevel()
Level two = f_blankLevel()
Level three = f_blankLevel()
float r1 = -1.0e20
float r2 = -1.0e20
float r3 = -1.0e20
if array.size(zs) > 0
for i = 0 to array.size(zs) - 1
StoredZone z = array.get(zs, i)
float mid = (z.upper + z.lower) * 0.5
bool relevantSide = role == 1 ? mid <= close + atr * 0.4 : mid >= close - atr * 0.4
if z.role == role and z.touches >= minimum and z.state != 5 and relevantSide
float score = f_zoneQuality(z) - math.min(math.abs(mid - close) / math.max(atr, syminfo.mintick), 60.0) * 1.2
if score > r1
three := two
two := one
one := f_levelCopy(z)
r3 := r2
r2 := r1
r1 := score
else if score > r2
three := two
two := f_levelCopy(z)
r3 := r2
r2 := score
else if score > r3
three := f_levelCopy(z)
r3 := score
[one, two, three]
f_fitTrend(array<PivotPoint> ps, int role, int minTouches, int minGap, int minSpan, float atr, string skipKey, int afterTime) =>
Trend best = f_blankTrend()
float bestScore = -1.0e20
int n = array.size(ps)
if n >= 2 and atr > 0
for i = 0 to n - 2
PivotPoint recent = array.get(ps, i)
for j = i + 1 to n - 1
PivotPoint old = array.get(ps, j)
string key = str.tostring(old.stamp) + ":" + str.tostring(recent.stamp) + ":" + str.tostring(role)
if recent.idx - old.idx >= minSpan and recent.stamp > old.stamp and key != skipKey and (na(afterTime) or recent.stamp > afterTime)
float slope = (recent.value - old.value) / float(recent.stamp - old.stamp)
float normSlope = math.abs(slope) * timeframe.in_seconds() * 1000 / atr
int touches = 0
int violations = 0
int lastAccepted = na
for k = 0 to n - 1
PivotPoint p = array.get(ps, k)
if p.idx >= old.idx
float yp = old.value + slope * (p.stamp - old.stamp)
float delta = p.value - yp
if math.abs(delta) <= atr * 0.25 and (na(lastAccepted) or math.abs(p.idx - lastAccepted) >= minGap)
touches += 1
lastAccepted := p.idx
if (role == -1 and delta > atr * 0.25) or (role == 1 and delta < -atr * 0.25)
violations += 1
float now = old.value + slope * (time_close - old.stamp)
bool side = role == 1 ? now <= close + atr * 0.35 : now >= close - atr * 0.35
float distance = math.abs(now - close) / atr
if touches >= minTouches and violations <= 1 and normSlope <= 0.35 and distance <= 12 and side
float score = touches * 20 + math.min(recent.idx - old.idx, 400) * 0.04 - violations * 15 - distance
if score > bestScore
bestScore := score
best := Trend.new(key, old.stamp, recent.stamp, old.value, recent.value, time_close, role, touches, violations, minTouches >= 3 ? 1 : 0, na, 0, score)
best
f_progressTrend(Trend t, float atr, int retestWindowMs) =>
int broken = 0
int retested = 0
int failed = 0
if t.id != "" and t.known <= time and t.state != 4
float yp = f_trendY(t, time_close)
float previous = f_trendY(t, time_close[1])
if t.state == 1
bool up = t.role == -1 and close > yp + atr * 0.10 and close[1] <= previous + atr * 0.10
bool dn = t.role == 1 and close < yp - atr * 0.10 and close[1] >= previous - atr * 0.10
if up or dn
broken := up ? 1 : -1
t.breakDirection := broken
t.breakAt := time_close
t.state := 2
else if t.state == 2 and time_close > t.breakAt
bool wrong = t.breakDirection == 1 ? close < yp - atr * 0.30 : close > yp + atr * 0.30
bool touched = low <= yp + atr * 0.30 and high >= yp - atr * 0.30
bool held = t.breakDirection == 1 ? close >= yp : close <= yp
if wrong
failed := t.breakDirection
t.state := 4
else if touched and held
retested := t.breakDirection
t.role := t.breakDirection
t.state := 3
else if time_close - t.breakAt > retestWindowMs
t.state := 4
else if t.state == 3
bool wrong = t.role == 1 ? close < yp - atr * 0.30 : close > yp + atr * 0.30
if wrong or time_close - t.breakAt > retestWindowMs * 3
t.state := 4
[broken, retested, failed]
// Time-coordinate OLS/Huber. Each residual is evaluated at its own sample time.
// On evenly spaced candles this is the ordinary bar-index regression exactly.
f_regression(int count, bool robust) =>
Channel out = f_blankChannel()
int n = math.min(count, bar_index + 1)
if n >= 20 and not na(close[n-1]) and not na(time_close[n-1])
int start = time_close[n-1]
float unit = math.max(1.0, timeframe.in_seconds() * 1000.0)
float sx = 0.0
float sy = 0.0
float sxx = 0.0
float sxy = 0.0
for i = 0 to n - 1
float x = (time_close[i] - start) / unit
float y = close[i]
sx += x
sy += y
sxx += x * x
sxy += x * y
float denom = n * sxx - sx * sx
float slope = denom > 0 ? (n * sxy - sx * sy) / denom : 0.0
float intercept = sy / n - slope * sx / n
if robust
// Fixed three IRLS iterations; no optimization against future returns.
for iteration = 0 to 2
array<float> residuals = array.new<float>()
for i = 0 to n - 1
float x = (time_close[i] - start) / unit
array.push(residuals, math.abs(close[i] - intercept - slope * x))
float scale = math.max(array.median(residuals) * 1.4826, syminfo.mintick)
float sw = 0.0
float swx = 0.0
float swy = 0.0
float swxx = 0.0
float swxy = 0.0
for i = 0 to n - 1
float x = (time_close[i] - start) / unit
float y = close[i]
float residual = math.abs(y - intercept - slope * x)
float weight = residual <= 1.5 * scale ? 1.0 : 1.5 * scale / residual
sw += weight
swx += weight * x
swy += weight * y
swxx += weight * x * x
swxy += weight * x * y
float d = sw * swxx - swx * swx
slope := d > 0 ? (sw * swxy - swx * swy) / d : 0.0
intercept := sw > 0 ? (swy - slope * swx) / sw : sy / n
float sse = 0.0
float sst = 0.0
array<float> absResiduals = array.new<float>()
for i = 0 to n - 1
float x = (time_close[i] - start) / unit
float residual = close[i] - (intercept + slope * x)
sse += residual * residual
sst += math.pow(close[i] - sy / n, 2)
if robust
array.push(absResiduals, math.abs(residual))
float scale = robust ? array.median(absResiduals) * 1.4826 : math.sqrt(math.max(0.0, sse / n))
float end = intercept + slope * (time_close - start) / unit
float quality = sst > 0 ? math.max(0.0, 1.0 - sse / sst) : 1.0
out := Channel.new(time_close, start, time_close, intercept, end, math.max(scale, syminfo.mintick), quality, n, time_close, 1, 0)
out
export calculate(simple int pivotBars = 5, simple int minTouches = 2, simple int touchGap = 5, simple int capacity = 48, simple int maximumAge = 2000, simple int regressionLength = 100, simple string regressionMode = "Rolling OLS", simple float deviations = 2.0, simple int acceptanceCloses = 2) =>
if barstate.isfirst and (pivotBars < 2 or pivotBars > 20 or minTouches < 2 or minTouches > 6 or touchGap < 2 or capacity < 6 or capacity > 80 or maximumAge < 200 or maximumAge > 4000 or regressionLength < 20 or regressionLength > 250 or deviations <= 0 or acceptanceCloses < 1 or acceptanceCloses > 3)
runtime.error("ITBFStructureEngine: configuration is outside the bounded v1 API limits.")
float atr = ta.atr(14)
float ph = ta.pivothigh(high, pivotBars, pivotBars)
float pl = ta.pivotlow(low, pivotBars, pivotBars)
float dHigh = ta.highest(high, 20)
float dLow = ta.lowest(low, 20)
var array<StoredZone> zones = array.new<StoredZone>()
var array<PivotPoint> highs = array.new<PivotPoint>()
var array<PivotPoint> lows = array.new<PivotPoint>()
var Trend supportLine = f_blankTrend()
var Trend resistanceLine = f_blankTrend()
var Trend developingSupport = f_blankTrend()
var Trend developingResistance = f_blankTrend()
var string retiredSupport = ""
var string retiredResistance = ""
var int resAfter = na
var int supAfter = na
var int anchorIndex = 0
var Channel frozen = f_blankChannel()
var int freezeIndex = 0
var int channelBeyond = 0
var int channelDir = 0
var int channelInside = 0
int zoneBreak = 0
int zoneRetest = 0
int zoneFailed = 0
int evicted = 0
int retestMs = int(timeframe.in_seconds() * 1000) * 12
// Evaluate known, frozen zones BEFORE ingesting today's newly confirmed pivots.
if array.size(zones) > 0 and not na(atr)
for i = 0 to array.size(zones) - 1
StoredZone z = array.get(zones, i)
if z.state != 5 and z.known <= time
bool beyond = z.role == 1 ? close < z.lower - atr * 0.10 : close > z.upper + atr * 0.10
if beyond
z.beyond += 1
z.state := 2
if z.beyond >= acceptanceCloses
z.role := -z.role
z.flips += 1
z.revision += 1
z.effective := time_close
z.acceptedAt := time_close
z.acceptedIndex := bar_index
z.retested := false
z.state := z.flips > 3 ? 5 : 3
zoneBreak := z.role
z.beyond := 0
else
if z.beyond > 0
zoneFailed := -z.role
z.beyond := 0
if z.state == 2
z.state := z.touches >= minTouches ? 1 : 0
bool intersects = low <= z.upper and high >= z.lower
bool holds = z.role == 1 ? close > z.upper : close < z.lower
if z.state != 5 and intersects and z.armed and bar_index - z.lastTouchIndex >= touchGap
z.touches += 1
z.lastTouchIndex := bar_index
z.lastTouchTime := time_close
z.armed := false
if z.touches >= minTouches and z.state == 0
z.state := 1
z.effective := time_close
if z.state == 3 and not z.retested and bar_index > nz(z.acceptedIndex, bar_index) and intersects and holds
z.retested := true
zoneRetest := z.role
if (z.role == 1 and low > z.upper + atr * 0.5) or (z.role == -1 and high < z.lower - atr * 0.5)
z.armed := true
if bar_index - z.lastTouchIndex > maximumAge
z.state := 5
[sb, sr, sf] = f_progressTrend(supportLine, atr, retestMs)
[rb, rr, rf] = f_progressTrend(resistanceLine, atr, retestMs)
if supportLine.state == 4
retiredSupport := supportLine.id
supAfter := nz(supportLine.breakAt, supportLine.known)
if resistanceLine.state == 4
retiredResistance := resistanceLine.id
resAfter := nz(resistanceLine.breakAt, resistanceLine.known)
bool newPivot = not na(ph) or not na(pl)
if not na(ph) and not na(atr)
f_addPivot(highs, ph, time_close[pivotBars], bar_index - pivotBars)
evicted := f_addZone(zones, ph, -1, time_close[pivotBars], bar_index - pivotBars, atr, touchGap, capacity)
if not na(pl) and not na(atr)
f_addPivot(lows, pl, time_close[pivotBars], bar_index - pivotBars)
int e = f_addZone(zones, pl, 1, time_close[pivotBars], bar_index - pivotBars, atr, touchGap, capacity)
evicted := e != 0 ? e : evicted
if newPivot and not na(atr)
if supportLine.id == "" or supportLine.state == 4
supportLine := f_fitTrend(lows, 1, 3, touchGap, 12, atr, retiredSupport, supAfter)
if resistanceLine.id == "" or resistanceLine.state == 4
resistanceLine := f_fitTrend(highs, -1, 3, touchGap, 12, atr, retiredResistance, resAfter)
developingSupport := f_fitTrend(lows, 1, 2, touchGap, 8, atr, retiredSupport, supAfter)
developingResistance := f_fitTrend(highs, -1, 2, touchGap, 8, atr, retiredResistance, resAfter)
// Old confirmed lines age out; new fits take new identities. No refit-cross events.
if supportLine.id != "" and time_close - supportLine.known > retestMs * 40
supportLine.state := 4
if resistanceLine.id != "" and time_close - resistanceLine.known > retestMs * 40
resistanceLine.state := 4
int trendBreak = rb != 0 ? rb : sb
int trendRetest = rr != 0 ? rr : sr
int trendFailed = rf != 0 ? rf : sf
if zoneBreak != 0 or trendBreak != 0
anchorIndex := bar_index
int length = regressionMode == "Structure anchored" ? math.min(regressionLength, bar_index - anchorIndex + 1) : regressionLength
Channel rolling = f_regression(length, regressionMode == "Robust Huber")
int channelBreak = 0
if frozen.count >= 20 and frozen.known <= time and not na(atr)
float mid = f_channelY(frozen, time_close)
int side = close > mid + frozen.sigma * deviations + atr * 0.10 ? 1 : close < mid - frozen.sigma * deviations - atr * 0.10 ? -1 : 0
if frozen.state == 1
if side != 0
channelBeyond := side == channelDir ? channelBeyond + 1 : 1
channelDir := side
if channelBeyond >= acceptanceCloses
frozen.state := 2
frozen.breakDirection := side
channelBreak := side
channelInside := 0
freezeIndex := bar_index
else
channelBeyond := 0
channelDir := 0
else
channelInside := side == 0 ? channelInside + 1 : 0
bool newFitAllowed = frozen.count < 20 or (frozen.state == 1 and channelBeyond == 0 and bar_index - freezeIndex >= 20) or (frozen.state == 2 and (channelInside >= 5 or bar_index - freezeIndex >= regressionLength))
if rolling.count >= 20 and newFitAllowed
frozen := rolling.copy()
freezeIndex := bar_index
channelBeyond := 0
channelInside := 0
channelDir := 0
if array.size(zones) > 0
for z in zones
if z.state == 0 and z.touches >= minTouches
z.state := 1
z.effective := time_close
[s1, s2, s3] = f_bestLevels(zones, 1, minTouches, atr)
[r1, r2, r3] = f_bestLevels(zones, -1, minTouches, atr)
Snapshot out = Snapshot.new()
out.ticker := syminfo.tickerid
out.tf := timeframe.period
out.opened := time
out.closed := time_close
out.index := bar_index
out.atr := atr
out.ready := not na(atr) and bar_index >= pivotBars * 2
out.s1 := s1
out.s2 := s2
out.s3 := s3
out.r1 := r1
out.r2 := r2
out.r3 := r3
// These copy scalar fields only. The mutable source state NEVER leaves this function.
out.supportLine := supportLine.copy()
out.resistanceLine := resistanceLine.copy()
out.developingSupport := developingSupport.copy()
out.developingResistance := developingResistance.copy()
out.rolling := rolling.copy()
out.frozen := frozen.copy()
out.rangeValid := s1.id != 0 and r1.id != 0 and r1.lower > s1.upper + atr and s1.state != 2 and r1.state != 2
out.rangeMid := out.rangeValid ? (s1.upper + r1.lower) * 0.5 : na
out.donHigh := dHigh
out.donLow := dLow
out.zoneBreak := zoneBreak
out.zoneRetest := zoneRetest
out.zoneFailed := zoneFailed
out.trendBreak := trendBreak
out.trendRetest := trendRetest
out.trendFailed := trendFailed
out.channelBreak := channelBreak
out.evictedId := evicted
out.evictionReason := evicted != 0 ? "CAPACITY: lowest age-adjusted significance" : ""
out.storedZones := array.size(zones)
out
// Use ONLY in a higher-timeframe request with lookahead_on. Immutable snapshot[1].
export confirmed(simple int pivotBars = 5, simple int minTouches = 2, simple int touchGap = 5, simple int capacity = 48, simple int maximumAge = 2000, simple int regressionLength = 100, simple string regressionMode = "Rolling OLS", simple float deviations = 2.0, simple int acceptanceCloses = 2) =>
Snapshot current = calculate(pivotBars, minTouches, touchGap, capacity, maximumAge, regressionLength, regressionMode, deviations, acceptanceCloses)
current[1]
f_lookup(Snapshot s, int id, int rev) =>
bool found = false
if not na(s)
array<Level> ls = array.from(s.s1, s.s2, s.s3, s.r1, s.r2, s.r3)
for z in ls
if z.id == id and z.revision == rev and z.state != 2 and z.state != 5
found := true
found
// Child-timeframe observations. Use prior available snapshot, never today's refit.
export observe(Snapshot available, float rsi, bool requireRSI = false, float minimumRsiMove = 3.0, float deviations = 2.0) =>
float atr = ta.atr(14)
Snapshot prior = available[1]
Events e = Events.new()
var int setupBar = na
var Level setup = na
var float rejectionClose = na
var float rejectionHigh = na
var float rejectionLow = na
var float rejectionRsi = na
var string observedLineUp = ""
var string observedLineDown = ""
var int observedChannel = 0
if barstate.isconfirmed and not na(prior) and prior.ready
if not na(setupBar) and bar_index == setupBar + 1 and not na(setup)
bool intact = f_lookup(prior, setup.id, setup.revision)
bool buy = setup.role == 1 and close > open and close > rejectionClose and close > setup.upper
bool sell = setup.role == -1 and close < open and close < rejectionClose and close < setup.lower
bool holds = setup.role == 1 ? low >= setup.lower - 0.8 * atr : high <= setup.upper + 0.8 * atr
bool mom = not requireRSI or (setup.role == 1 ? rsi - rejectionRsi >= minimumRsiMove : rejectionRsi - rsi >= minimumRsiMove)
e.confirmBuy := intact and holds and mom and buy
e.confirmSell := intact and holds and mom and sell
if e.confirmBuy or e.confirmSell
e.zoneId := setup.id
e.zoneRevision := setup.revision
e.boundary := setup.role == 1 ? setup.upper : setup.lower
e.invalidation := setup.role == 1 ? math.min(low, rejectionLow) - atr * 0.2 : math.max(high, rejectionHigh) + atr * 0.2
e.eventId := prior.ticker + "|" + prior.tf + "|" + str.tostring(setup.id) + "|" + str.tostring(setup.revision) + "|CONFIRM|" + str.tostring(time_close)
setupBar := na
setup := na
array<Level> ls = array.from(prior.s1, prior.s2, prior.s3, prior.r1, prior.r2, prior.r3)
float bestQ = -1.0
float candleSpan = math.max(high - low, syminfo.mintick)
for z in ls
bool valid = z.id != 0 and z.known <= time and z.effective <= time and z.state != 5 and z.state != 2
if valid
bool touch = low <= z.upper and high >= z.lower
bool buy = z.role == 1 and touch and close > z.upper and (close - low) / candleSpan >= 0.60 and (math.min(open, close) - low) / candleSpan >= 0.18 and low >= z.lower - atr * 0.8
bool sell = z.role == -1 and touch and close < z.lower and (high - close) / candleSpan >= 0.60 and (high - math.max(open, close)) / candleSpan >= 0.18 and high <= z.upper + atr * 0.8
if (buy or sell) and z.quality > bestQ
bestQ := z.quality
setup := z.copy()
setupBar := bar_index
rejectionClose := close
rejectionHigh := high
rejectionLow := low
rejectionRsi := rsi
e.rejectionBuy := buy
e.rejectionSell := sell
bool up = z.role == -1 and close > z.upper + atr * 0.10 and close[1] <= z.upper + atr * 0.10
bool dn = z.role == 1 and close < z.lower - atr * 0.10 and close[1] >= z.lower - atr * 0.10
if up
e.breachUp := true
e.breachedResistance := z.upper
if dn
e.breachDown := true
e.breachedSupport := z.lower
Trend rt = prior.resistanceLine
Trend st = prior.supportLine
if rt.id != "" and rt.state == 1 and rt.known <= time
float now = f_trendY(rt, time_close)
float prev = f_trendY(rt, time_close[1])
if close > now + atr * 0.10 and close[1] <= prev + atr * 0.10 and rt.id != observedLineUp
e.lineBreakUp := true
observedLineUp := rt.id
if st.id != "" and st.state == 1 and st.known <= time
float now = f_trendY(st, time_close)
float prev = f_trendY(st, time_close[1])
if close < now - atr * 0.10 and close[1] >= prev - atr * 0.10 and st.id != observedLineDown
e.lineBreakDown := true
observedLineDown := st.id
Channel ch = prior.frozen
if ch.count >= 20 and ch.known <= time and ch.id != observedChannel
float mid = f_channelY(ch, time_close)
float prev = f_channelY(ch, time_close[1])
e.channelUp := close > mid + ch.sigma * deviations + atr * 0.10 and close[1] <= prev + ch.sigma * deviations + atr * 0.10
e.channelDown := close < mid - ch.sigma * deviations - atr * 0.10 and close[1] >= prev - ch.sigma * deviations - atr * 0.10
if e.channelUp or e.channelDown
observedChannel := ch.id
e
// Nearest obstacle uses the near edge, not the far edge or the prettiest band.
export obstacle(Snapshot s, int direction, float entry) =>
float nearest = na
int id = 0
if not na(s) and s.ready
array<Level> levels = direction == 1 ? array.from(s.r1, s.r2, s.r3) : array.from(s.s1, s.s2, s.s3)
for z in levels
float price = direction == 1 ? z.lower : z.upper
if z.id != 0 and z.effective <= time_close and z.state != 5 and (price - entry) * direction > 0
if na(nearest) or (price - nearest) * direction < 0
nearest := price
id := z.id
[nearest, id]
f_drawLine(Renderer r, int slot, bool visible, int t1, float y1, int t2, float y2, color col, string style, int width) =>
line obj = array.get(r.lines, slot)
if visible and not na(t1) and not na(t2) and not na(y1) and not na(y2)
if na(obj)
obj := line.new(t1, y1, t2, y2, xloc=xloc.bar_time, color=col, width=width, style=style)
array.set(r.lines, slot, obj)
else
line.set_xy1(obj, t1, y1)
line.set_xy2(obj, t2, y2)
line.set_color(obj, col)
line.set_style(obj, style)
line.set_width(obj, width)
else if not na(obj)
line.delete(obj)
array.set(r.lines, slot, na)
true
export clearRenderer(Renderer r) =>
for i = 0 to array.size(r.zones) - 1
box.delete(array.get(r.zones, i))
array.set(r.zones, i, na)
for i = 0 to array.size(r.lines) - 1
line.delete(array.get(r.lines, i))
array.set(r.lines, i, na)
for i = 0 to array.size(r.labels) - 1
label.delete(array.get(r.labels, i))
array.set(r.labels, i, na)
true
// Drawing functions run only in the HOST chart context, never inside request.*.
export render(Renderer r, Snapshot s, bool showZones, bool showLines, bool showDeveloping, bool showChannel, bool useRolling, bool showMidpoint, float deviations, int endTime, color supportColor, color resistanceColor, color channelColor, int visiblePerSide = 2) =>
if barstate.islast
if na(s) or not s.ready
clearRenderer(r)
else
array<Level> levels = array.from(s.s1, s.s2, s.s3, s.r1, s.r2, s.r3)
for i = 0 to 5
Level z = array.get(levels, i)
bool show = showZones and i % 3 < visiblePerSide and z.id != 0 and z.state != 5
box obj = array.get(r.zones, i)
if show
color col = z.role == 1 ? supportColor : resistanceColor
string tag = s.tf + (z.role == 1 ? " SUPPORT" : " RESISTANCE") + (z.flips > 0 ? " FLIPPED" : "") + " | " + str.tostring(z.touches) + " tests | Q" + str.tostring(z.quality, "#")
// Left edge is current qualification/role availability, never the older pivot origin.
if na(obj)
obj := box.new(z.effective, z.upper, endTime, z.lower, xloc=xloc.bar_time, border_color=col, bgcolor=color.new(col, 89), text=tag, text_size=size.tiny, text_color=col, text_halign=text.align_right)
array.set(r.zones, i, obj)
else
box.set_lefttop(obj, z.effective, z.upper)
box.set_rightbottom(obj, endTime, z.lower)
box.set_border_color(obj, col)
box.set_bgcolor(obj, color.new(col, 89))
box.set_text(obj, tag)
box.set_text_color(obj, col)
else if not na(obj)
box.delete(obj)
array.set(r.zones, i, na)
array<Trend> ts = array.from(s.supportLine, s.resistanceLine, s.developingSupport, s.developingResistance)
for i = 0 to 3
Trend tr = array.get(ts, i)
float nowY = f_trendY(tr, endTime)
bool good = tr.id != "" and tr.state != 4 and math.abs(nowY - close) <= s.atr * 15 and nowY > 0
bool show = i < 2 ? showLines : showLines and showDeveloping and tr.id != (i == 2 ? s.supportLine.id : s.resistanceLine.id)
color col = tr.role == 1 ? supportColor : resistanceColor
f_drawLine(r, i, good and show, tr.x1, tr.y1, endTime, nowY, color.new(col, i >= 2 ? 55 : 10), i >= 2 ? line.style_dotted : tr.state == 1 ? line.style_solid : line.style_dashed, i < 2 ? 2 : 1)
Channel ch = useRolling ? s.rolling : s.frozen
float mid = f_channelY(ch, endTime)
bool channelOK = showChannel and ch.count >= 20 and math.abs(mid - close) <= s.atr * 15
for i = 0 to 2
float offset = (i - 1) * ch.sigma * deviations
f_drawLine(r, 4 + i, channelOK, ch.x1, ch.y1 + offset, endTime, mid + offset, color.new(channelColor, i == 1 ? 40 : 5), ch.state == 2 ? line.style_dotted : i == 1 ? line.style_dashed : line.style_solid, 1)
f_drawLine(r, 7, showMidpoint and s.rangeValid, s.closed, s.rangeMid, endTime, s.rangeMid, color.new(color.gray, 25), line.style_dotted, 1)
label note = array.get(r.labels, 0)
string noteText = s.tf + " | " + (useRolling ? "ROLLING FIT" : ch.state == 2 ? "CHANNEL BROKEN" : "FROZEN CHANNEL") + " | R2 " + str.tostring(ch.r2, "#.##") + " | " + str.tostring(ch.count) + " bars"
if channelOK
if na(note)
note := label.new(endTime, mid, noteText, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(channelColor, 85), textcolor=channelColor, size=size.tiny)
array.set(r.labels, 0, note)
else
label.set_xy(note, endTime, mid)
label.set_text(note, noteText)
else if not na(note)
label.delete(note)
array.set(r.labels, 0, na)
true
// ============================================================================
// Advanced context -> existing Swing consumer contracts.
// These change structural CONTEXT, not main BUY/SELL or frozen-target policy.
// ============================================================================
f_preferLevel(Level local, Level inherited, bool useInherited, float price, float atr) =>
Level chosen = local
if useInherited and not na(inherited) and inherited.id != 0 and inherited.state != 2 and inherited.state != 5
float hiDist = math.abs((inherited.upper + inherited.lower) * 0.5 - price)
float loDist = not na(local) and local.id != 0 ? math.abs((local.upper + local.lower) * 0.5 - price) : 1.0e20
// Nearest meaningful obstacle, with a small source-timeframe preference.
if hiDist <= loDist + atr * 0.25
chosen := inherited
chosen
export advancedSR(LegacySRConfig c, Snapshot local, Snapshot higher, bool inherit, Events le, Events he) =>
LegacySRResult out = LegacySRResult.new()
float atr = ta.atr(14)
Level sup = local.s1
Level res = local.r1
if not na(higher)
sup := f_preferLevel(sup, higher.s1, inherit, close, atr)
res := f_preferLevel(res, higher.r1, inherit, close, atr)
float support = sup.id != 0 ? (sup.lower + sup.upper) * 0.5 : na
float resistance = res.id != 0 ? (res.lower + res.upper) * 0.5 : na
float tolerance = atr * c.clusterDistanceMult
out.support := support
out.resistance := resistance
out.src := close
out.clusterDistance := tolerance
// Preserve exact legacy primitives for the liquidity consumer's chosen settings.
out.pivotH := ta.pivothigh(high, c.pivotLeft, c.pivotRight)
out.pivotL := ta.pivotlow(low, c.pivotLeft, c.pivotRight)
out.srSupportTouches := sup.touches
out.srResistanceTouches := res.touches
out.srSupportSpan := sup.spanBars
out.srResistanceSpan := res.spanBars
out.isNearSupport := not na(support) and low <= sup.upper + tolerance and high >= sup.lower - tolerance
out.isNearResistance := not na(resistance) and high >= res.lower - tolerance and low <= res.upper + tolerance
out.allowBuy := na(resistance) or not out.isNearResistance or close > res.upper
out.allowSell := na(support) or not out.isNearSupport or close < sup.lower
out.srBreakUpEvent := le.breachUp or (inherit and he.breachUp)
out.srBreakDnEvent := le.breachDown or (inherit and he.breachDown)
out.srBreakUpLevelNow := le.breachUp ? le.breachedResistance : inherit and he.breachUp ? he.breachedResistance : na
out.srBreakDnLevelNow := le.breachDown ? le.breachedSupport : inherit and he.breachDown ? he.breachedSupport : na
out.retestResistance := sup.flips > 0 ? support : na
out.retestSupport := res.flips > 0 ? resistance : na
out.isNearRetestResistance := sup.flips > 0 and out.isNearSupport
out.isNearRetestSupport := res.flips > 0 and out.isNearResistance
out.srRetestBull := barstate.isconfirmed and local.zoneRetest == 1
out.srRetestBear := barstate.isconfirmed and local.zoneRetest == -1
out
export advancedTL(LegacyTLConfig c, Snapshot local, Snapshot higher, bool inherit, Events le, Events he) =>
LegacyTLResult out = LegacyTLResult.new()
Trend st = local.supportLine
Trend rt = local.resistanceLine
if inherit and not na(higher)
if higher.supportLine.id != "" and higher.supportLine.state == 1
st := higher.supportLine
if higher.resistanceLine.id != "" and higher.resistanceLine.state == 1
rt := higher.resistanceLine
out.res_tl_y := rt.id != "" and rt.state == 1 ? f_trendY(rt, time_close) : na
out.sup_tl_y := st.id != "" and st.state == 1 ? f_trendY(st, time_close) : na
out.domResOldT := rt.x1
out.domResOldY := rt.y1
out.domResNewT := rt.x2
out.domResNewY := rt.y2
out.domResTouches := rt.touches
out.domSupOldT := st.x1
out.domSupOldY := st.y1
out.domSupNewT := st.x2
out.domSupNewY := st.y2
out.domSupTouches := st.touches
// Source indices have no valid one-to-one mapping to chart indices. Keep na.
out.domResOldB := na
out.domResNewB := na
out.domSupOldB := na
out.domSupNewB := na
out.tlUpActive := rt.state == 2 and rt.breakDirection == 1
out.tlDnActive := st.state == 2 and st.breakDirection == -1
out.trend_break_up := le.lineBreakUp or (inherit and he.lineBreakUp)
out.trend_break_dn := le.lineBreakDown or (inherit and he.lineBreakDown)
out.trend_retest_up := barstate.isconfirmed and local.trendRetest == 1
out.trend_retest_dn := barstate.isconfirmed and local.trendRetest == -1
out.tlBreakUpFailedNow := barstate.isconfirmed and local.trendFailed == 1
out.tlBreakDnFailedNow := barstate.isconfirmed and local.trendFailed == -1
out.v14291Visual01Arg00 := c.v1429ViewContext and out.trend_break_up
out.v14291Visual01Arg03 := color.aqua
out.v14291Visual02Arg00 := c.v1429ViewContext and out.trend_break_dn
out.v14291Visual02Arg03 := color.fuchsia
out.v14291Visual03Arg00 := c.v1429ViewContext and out.trend_retest_up
out.v14291Visual03Arg03 := color.teal
out.v14291Visual04Arg00 := c.v1429ViewContext and out.trend_retest_dn
out.v14291Visual04Arg03 := color.purple
// Advanced numerical geometry is NOT recovered from line drawing handles.
out