PINE LIBRARY
업데이트됨 ContextAwarenessEngine

Library "ContextAwarenessEngine"
Shared "human contextual awareness" engine — structure memory,
zone memory, sequence engine, regime flags. Import this from any indicator
instead of rebuilding these primitives per-script (the bug pattern behind
Kurisko v1/v2's misfires: each indicator invents its own crude, unverified
context logic). FIRST DRAFT — verify every threshold before trusting it.
newStructureMemory(maxAgeBars, minMagnitudeATR)
Creates a new, empty structure memory.
Parameters:
maxAgeBars (int): bars after which a pivot is forgotten
minMagnitudeATR (float): minimum swing size (in ATR multiples) to be recorded — filters noise pivots
Returns: a fresh StructureMemory instance
prune(mem)
Prunes pivots older than maxAge. Call once per bar before recording.
Parameters:
mem (StructureMemory): the StructureMemory to prune
recordWithMagnitude(mem, price, swingMagnitude, atrVal, isLow, touchTolATR)
Preferred entry point: caller supplies the actual swing magnitude
(e.g. abs(pivotPrice - priorOppositePivotPrice)) so "significant vs noise"
reflects real swing size, not just ATR at a point.
Parameters:
mem (StructureMemory): the StructureMemory to update
price (float): the pivot price
swingMagnitude (float): the size of the swing this pivot represents (price units)
atrVal (float): current ATR — swingMagnitude is measured in ATR multiples against this
isLow (bool): true if this pivot is a swing LOW (directional override checks
for a genuinely lower low); false for a swing HIGH (checks for higher high).
Without this, a real break beyond an old level gets silently logged as a
mere "touch" of that level instead of a new, more extreme pivot — the exact
bug behind missing the deeper low in the circled BTCUSD chart area.
touchTolATR (float): tolerance (x ATR) for counting a revisit vs a new pivot
Returns: [isNew, matchedIndex] — isNew true if recorded as a fresh pivot, matchedIndex is the array index touched (-1 if new)
currentExtreme(mem, wantLowest)
Returns the actual current floor/ceiling in memory — lowest low
or highest high still tracked — regardless of its ATR-relative magnitude
at formation. This answers "where is price's real extreme right now,"
which mostSignificant() (magnitude-ranked) does NOT answer.
Parameters:
mem (StructureMemory): the StructureMemory to search
wantLowest (bool): true to find the lowest price (support floor), false for highest (ceiling)
Returns: the most extreme Pivot by raw price, or na fields if empty
isStale(p, maxTouches)
A level touched too many times has likely already been consumed —
flag it as stale so callers stop treating it as fresh, reliable liquidity.
Parameters:
p (Pivot): the Pivot to check
maxTouches (int): touches beyond this count are considered stale
mostSignificant(mem, maxTouches)
The single most "significant" pivot still in memory — largest
magnitude among NON-STALE pivots (excludes levels already ground through
maxTouches times, since those have likely been consumed already). This is
the closest analogue to "the obvious swing point a human's eye lands on
first" — but a human also discounts a level they've watched fail three
times already, which is what the staleness filter encodes.
Parameters:
mem (StructureMemory): the StructureMemory to search
maxTouches (int): touches beyond this exclude a pivot as stale (see isStale)
Returns: the most significant non-stale Pivot, or na fields if none qualify
newZone(top, bottom, validBars, kind)
Creates a new zone.
Parameters:
top (float): top of the zone
bottom (float): bottom of the zone
validBars (int): how many bars the zone stays "live" before expiring unfilled
kind (string): free-text label for what kind of zone this is
Returns: a fresh Zone
isFresh(z)
Checks whether a zone is still within its validity window.
Parameters:
z (Zone): the Zone to check
Returns: true if the zone hasn't expired
checkTouch(z, hi, lo)
Checks whether current price has entered the zone, and marks it
touched if so. Call once per bar for each active zone.
Parameters:
z (Zone): the Zone to check/update
hi (float): current bar high
lo (float): current bar low
Returns: true if price is inside the zone on this bar
isActiveReaction(z)
A zone counts as an active, meaningful reaction target only if
it's still fresh AND has actually been touched — "sweep happened, price
came back" not just "gap exists somewhere in memory."
Parameters:
z (Zone): the Zone to evaluate
entryPrice(z, aggressive)
Horner's two entry modes for an FVG zone: conservative waits for
the FULL gap fill and enters at the edge farthest into the zone (safer,
worse R:R, matches "wait for price to fill the entire gap" from her FVG
video); aggressive enters at the 50% midpoint/equilibrium (better R:R,
needs smaller size since it's a more precise level). Direction-aware via
z.kind so callers don't have to work out which edge is "far" themselves.
Parameters:
z (Zone): the Zone to compute an entry for (kind must be "FVG_BULL" or "FVG_BEAR")
aggressive (bool): true for the 50% midpoint entry, false for the far-edge conservative entry
Returns: the entry price, or na if z.kind isn't a recognized FVG type
stopPrice(z, atrVal, bufferATRmult)
The matching stop-loss reference: "beyond the far edge of the
FVG" per both Horner's video and this project's own Confluence Trading
Framework doc. A small ATR buffer is added so the stop isn't sitting
exactly on the boundary (which invites getting picked off by noise).
Parameters:
z (Zone): the Zone to compute a stop for
atrVal (float): current ATR, used for the buffer beyond the far edge
bufferATRmult (float): how far beyond the far edge to place the stop (x ATR)
newSequence(maxBars)
Creates a new idle sequence tracker.
Parameters:
maxBars (int): how many bars a sequence can sit at one stage before expiring
advance(seq, leg1, leg2, leg3)
Advances or resets a sequence given the state of its three legs.
Call once per bar with the three boolean conditions for THIS bar. Order is
enforced: leg2 only counts if stage is already >=1, leg3 only if stage is
already >=2 — mirrors bar_index-ordering without needing separate `>=` checks
at every call site.
Parameters:
seq (Sequence): the Sequence to advance
leg1 (bool): condition for stage 0->1 (e.g. liquidity sweep / zone touch)
leg2 (bool): condition for stage 1->2 (e.g. extreme / momentum confirmation)
leg3 (bool): condition for stage 2->3, i.e. the actual fire (e.g. divergence)
Returns: true on the exact bar the full sequence fires
describe(seq)
Human-readable status for a status-table row — this is the direct
answer to "why hasn't it fired yet," visible instead of a black-box boolean.
Parameters:
seq (Sequence): the Sequence to describe
trendRegime(src)
Trend regime from price vs EMA200 + VWAP, as used across this project.
Parameters:
src (float): typically `close`
Returns: "UP", "DOWN", or "NEUTRAL"
volRegime(atrVal, atrLookback)
Volatility regime relative to the instrument's own recent history —
avoids hardcoding an absolute number that only makes sense for one asset class.
Parameters:
atrVal (float): current ATR
atrLookback (int): bars to compare against for "normal" ATR
Returns: "HIGH", "LOW", or "NORMAL"
inSession(sessSpec, tz)
Parameters:
sessSpec (string)
tz (string)
htfRegime(htf)
Parameters:
htf (string)
newRegimeTracker()
updateRegime(rt, newRegime)
Parameters:
rt (RegimeTracker)
newRegime (string)
justStartedTrending(rt)
Parameters:
rt (RegimeTracker)
brokeStructure(closePrice, refPivot, isBullBreak)
Parameters:
closePrice (float)
refPivot (Pivot)
isBullBreak (bool)
newStructureState()
changeOfCharacter(ss, brokeBull, brokeBear)
Parameters:
ss (StructureState)
brokeBull (bool)
brokeBear (bool)
candleCharacter(o, h, l, c, avgBody)
Parameters:
o (float)
h (float)
l (float)
c (float)
avgBody (float)
confidence(pivotStale, regimeJustShifted, htfCharacter)
Parameters:
pivotStale (bool)
regimeJustShifted (bool)
htfCharacter (string)
pivotRelation(newPrice, priorPrice, isLowType, tol)
Parameters:
newPrice (float)
priorPrice (float)
isLowType (bool)
tol (float)
latestRelation(mem, isLowType, atrVal, maxTouches)
Parameters:
mem (StructureMemory)
isLowType (bool)
atrVal (float)
maxTouches (int)
newStructureTrend()
updateStructureTrend(st, relation, confirmAfter)
Parameters:
st (StructureTrend)
relation (string)
confirmAfter (int)
Pivot
A single tracked swing pivot with magnitude/age/touch context.
Fields:
price (series float)
barIndex (series int)
magnitude (series float)
touchCount (series int)
StructureMemory
A rolling memory of pivots (one instance for highs, one for lows).
Fields:
pivots (array<Pivot>)
maxAge (series int)
minMagATR (series float)
Zone
A price zone with a validity clock (Horner's age x visibility idea).
Fields:
top (series float)
bottom (series float)
createdBar (series int)
validBars (series int)
touched (series bool)
kind (series string)
Sequence
Generic 3-stage sequence tracker.
Fields:
stage (series int)
stageBar (series int)
maxBars (series int)
RegimeTracker
Tracks a regime series over time so a TRANSITION (not just current
Fields:
current (series string)
previous (series string)
barsInCurrent (series int)
StructureState
Tracks the last confirmed structural break direction to detect CHoCH.
Fields:
lastBreakDir (series string)
StructureTrend
Running structure-trend state built from consecutive HH/HL vs LH/LL
Fields:
bias (series string)
consecutiveCount (series int)
Shared "human contextual awareness" engine — structure memory,
zone memory, sequence engine, regime flags. Import this from any indicator
instead of rebuilding these primitives per-script (the bug pattern behind
Kurisko v1/v2's misfires: each indicator invents its own crude, unverified
context logic). FIRST DRAFT — verify every threshold before trusting it.
newStructureMemory(maxAgeBars, minMagnitudeATR)
Creates a new, empty structure memory.
Parameters:
maxAgeBars (int): bars after which a pivot is forgotten
minMagnitudeATR (float): minimum swing size (in ATR multiples) to be recorded — filters noise pivots
Returns: a fresh StructureMemory instance
prune(mem)
Prunes pivots older than maxAge. Call once per bar before recording.
Parameters:
mem (StructureMemory): the StructureMemory to prune
recordWithMagnitude(mem, price, swingMagnitude, atrVal, isLow, touchTolATR)
Preferred entry point: caller supplies the actual swing magnitude
(e.g. abs(pivotPrice - priorOppositePivotPrice)) so "significant vs noise"
reflects real swing size, not just ATR at a point.
Parameters:
mem (StructureMemory): the StructureMemory to update
price (float): the pivot price
swingMagnitude (float): the size of the swing this pivot represents (price units)
atrVal (float): current ATR — swingMagnitude is measured in ATR multiples against this
isLow (bool): true if this pivot is a swing LOW (directional override checks
for a genuinely lower low); false for a swing HIGH (checks for higher high).
Without this, a real break beyond an old level gets silently logged as a
mere "touch" of that level instead of a new, more extreme pivot — the exact
bug behind missing the deeper low in the circled BTCUSD chart area.
touchTolATR (float): tolerance (x ATR) for counting a revisit vs a new pivot
Returns: [isNew, matchedIndex] — isNew true if recorded as a fresh pivot, matchedIndex is the array index touched (-1 if new)
currentExtreme(mem, wantLowest)
Returns the actual current floor/ceiling in memory — lowest low
or highest high still tracked — regardless of its ATR-relative magnitude
at formation. This answers "where is price's real extreme right now,"
which mostSignificant() (magnitude-ranked) does NOT answer.
Parameters:
mem (StructureMemory): the StructureMemory to search
wantLowest (bool): true to find the lowest price (support floor), false for highest (ceiling)
Returns: the most extreme Pivot by raw price, or na fields if empty
isStale(p, maxTouches)
A level touched too many times has likely already been consumed —
flag it as stale so callers stop treating it as fresh, reliable liquidity.
Parameters:
p (Pivot): the Pivot to check
maxTouches (int): touches beyond this count are considered stale
mostSignificant(mem, maxTouches)
The single most "significant" pivot still in memory — largest
magnitude among NON-STALE pivots (excludes levels already ground through
maxTouches times, since those have likely been consumed already). This is
the closest analogue to "the obvious swing point a human's eye lands on
first" — but a human also discounts a level they've watched fail three
times already, which is what the staleness filter encodes.
Parameters:
mem (StructureMemory): the StructureMemory to search
maxTouches (int): touches beyond this exclude a pivot as stale (see isStale)
Returns: the most significant non-stale Pivot, or na fields if none qualify
newZone(top, bottom, validBars, kind)
Creates a new zone.
Parameters:
top (float): top of the zone
bottom (float): bottom of the zone
validBars (int): how many bars the zone stays "live" before expiring unfilled
kind (string): free-text label for what kind of zone this is
Returns: a fresh Zone
isFresh(z)
Checks whether a zone is still within its validity window.
Parameters:
z (Zone): the Zone to check
Returns: true if the zone hasn't expired
checkTouch(z, hi, lo)
Checks whether current price has entered the zone, and marks it
touched if so. Call once per bar for each active zone.
Parameters:
z (Zone): the Zone to check/update
hi (float): current bar high
lo (float): current bar low
Returns: true if price is inside the zone on this bar
isActiveReaction(z)
A zone counts as an active, meaningful reaction target only if
it's still fresh AND has actually been touched — "sweep happened, price
came back" not just "gap exists somewhere in memory."
Parameters:
z (Zone): the Zone to evaluate
entryPrice(z, aggressive)
Horner's two entry modes for an FVG zone: conservative waits for
the FULL gap fill and enters at the edge farthest into the zone (safer,
worse R:R, matches "wait for price to fill the entire gap" from her FVG
video); aggressive enters at the 50% midpoint/equilibrium (better R:R,
needs smaller size since it's a more precise level). Direction-aware via
z.kind so callers don't have to work out which edge is "far" themselves.
Parameters:
z (Zone): the Zone to compute an entry for (kind must be "FVG_BULL" or "FVG_BEAR")
aggressive (bool): true for the 50% midpoint entry, false for the far-edge conservative entry
Returns: the entry price, or na if z.kind isn't a recognized FVG type
stopPrice(z, atrVal, bufferATRmult)
The matching stop-loss reference: "beyond the far edge of the
FVG" per both Horner's video and this project's own Confluence Trading
Framework doc. A small ATR buffer is added so the stop isn't sitting
exactly on the boundary (which invites getting picked off by noise).
Parameters:
z (Zone): the Zone to compute a stop for
atrVal (float): current ATR, used for the buffer beyond the far edge
bufferATRmult (float): how far beyond the far edge to place the stop (x ATR)
newSequence(maxBars)
Creates a new idle sequence tracker.
Parameters:
maxBars (int): how many bars a sequence can sit at one stage before expiring
advance(seq, leg1, leg2, leg3)
Advances or resets a sequence given the state of its three legs.
Call once per bar with the three boolean conditions for THIS bar. Order is
enforced: leg2 only counts if stage is already >=1, leg3 only if stage is
already >=2 — mirrors bar_index-ordering without needing separate `>=` checks
at every call site.
Parameters:
seq (Sequence): the Sequence to advance
leg1 (bool): condition for stage 0->1 (e.g. liquidity sweep / zone touch)
leg2 (bool): condition for stage 1->2 (e.g. extreme / momentum confirmation)
leg3 (bool): condition for stage 2->3, i.e. the actual fire (e.g. divergence)
Returns: true on the exact bar the full sequence fires
describe(seq)
Human-readable status for a status-table row — this is the direct
answer to "why hasn't it fired yet," visible instead of a black-box boolean.
Parameters:
seq (Sequence): the Sequence to describe
trendRegime(src)
Trend regime from price vs EMA200 + VWAP, as used across this project.
Parameters:
src (float): typically `close`
Returns: "UP", "DOWN", or "NEUTRAL"
volRegime(atrVal, atrLookback)
Volatility regime relative to the instrument's own recent history —
avoids hardcoding an absolute number that only makes sense for one asset class.
Parameters:
atrVal (float): current ATR
atrLookback (int): bars to compare against for "normal" ATR
Returns: "HIGH", "LOW", or "NORMAL"
inSession(sessSpec, tz)
Parameters:
sessSpec (string)
tz (string)
htfRegime(htf)
Parameters:
htf (string)
newRegimeTracker()
updateRegime(rt, newRegime)
Parameters:
rt (RegimeTracker)
newRegime (string)
justStartedTrending(rt)
Parameters:
rt (RegimeTracker)
brokeStructure(closePrice, refPivot, isBullBreak)
Parameters:
closePrice (float)
refPivot (Pivot)
isBullBreak (bool)
newStructureState()
changeOfCharacter(ss, brokeBull, brokeBear)
Parameters:
ss (StructureState)
brokeBull (bool)
brokeBear (bool)
candleCharacter(o, h, l, c, avgBody)
Parameters:
o (float)
h (float)
l (float)
c (float)
avgBody (float)
confidence(pivotStale, regimeJustShifted, htfCharacter)
Parameters:
pivotStale (bool)
regimeJustShifted (bool)
htfCharacter (string)
pivotRelation(newPrice, priorPrice, isLowType, tol)
Parameters:
newPrice (float)
priorPrice (float)
isLowType (bool)
tol (float)
latestRelation(mem, isLowType, atrVal, maxTouches)
Parameters:
mem (StructureMemory)
isLowType (bool)
atrVal (float)
maxTouches (int)
newStructureTrend()
updateStructureTrend(st, relation, confirmAfter)
Parameters:
st (StructureTrend)
relation (string)
confirmAfter (int)
Pivot
A single tracked swing pivot with magnitude/age/touch context.
Fields:
price (series float)
barIndex (series int)
magnitude (series float)
touchCount (series int)
StructureMemory
A rolling memory of pivots (one instance for highs, one for lows).
Fields:
pivots (array<Pivot>)
maxAge (series int)
minMagATR (series float)
Zone
A price zone with a validity clock (Horner's age x visibility idea).
Fields:
top (series float)
bottom (series float)
createdBar (series int)
validBars (series int)
touched (series bool)
kind (series string)
Sequence
Generic 3-stage sequence tracker.
Fields:
stage (series int)
stageBar (series int)
maxBars (series int)
RegimeTracker
Tracks a regime series over time so a TRANSITION (not just current
Fields:
current (series string)
previous (series string)
barsInCurrent (series int)
StructureState
Tracks the last confirmed structural break direction to detect CHoCH.
Fields:
lastBreakDir (series string)
StructureTrend
Running structure-trend state built from consecutive HH/HL vs LH/LL
Fields:
bias (series string)
consecutiveCount (series int)
릴리즈 노트
v2Added:
newBreakoutTracker(level, isBull)
Parameters:
level (float)
isBull (bool)
updateBreakoutTracker(bt, closePrice, sizeATRmult, inLiquiditySession, sweepSequenceCount, pivotAgreement, retraceWindowBars, holdWindowBars)
Parameters:
bt (BreakoutTracker)
closePrice (float)
sizeATRmult (float)
inLiquiditySession (bool)
sweepSequenceCount (int)
pivotAgreement (bool)
retraceWindowBars (int)
holdWindowBars (int)
newVolumeProfile(priceLow, priceHigh, numBuckets)
Parameters:
priceLow (float)
priceHigh (float)
numBuckets (int)
addBar(vp, barHigh, barLow, barVolume)
Parameters:
vp (VolumeProfile)
barHigh (float)
barLow (float)
barVolume (float)
pointOfControl(vp)
Parameters:
vp (VolumeProfile)
valueArea(vp, pct)
Parameters:
vp (VolumeProfile)
pct (float)
outsideValueArea(price, vaHigh, vaLow)
Parameters:
price (float)
vaHigh (float)
vaLow (float)
BreakoutTracker
Tracks one structural break from the moment it occurs through
Fields:
level (series float)
isBull (series bool)
breakBar (series int)
resolved (series bool)
score (series float)
conviction (series string)
VolumeProfile
A simple price-bucketed volume profile for one session/window.
Fields:
bucketPrices (array<float>)
bucketVolumes (array<float>)
bucketSize (series float)
Updated:
entryPrice(z, useCE)
Two entry modes for an FVG zone, corrected against primary
ICT-methodology sources (see this project's FVG_Comprehensive_Reference.md,
section 4) after an earlier version of this function had the labeling
backwards. Per every primary source checked: Consequent Encroachment (CE,
the 50% midpoint) is the STANDARD, higher-conviction entry reference --
"the equilibrium point... where institutional orders are often most
concentrated" -- not a risky/aggressive extreme. The far edge (requiring
a full gap fill before triggering) is the WEAKER, lower-probability
signal -- it's the "clean reaction" boundary, not a safe default. This
function previously called the far edge "conservative" and the midpoint
"aggressive," which inverted the actual risk/conviction relationship.
Direction-aware via z.kind so callers don't have to work out which edge
is "far" themselves.
Parameters:
z (Zone): the Zone to compute an entry for (kind must be "FVG_BULL" or "FVG_BEAR")
useCE (bool): true for the Consequent Encroachment (50% midpoint, standard/higher-conviction entry); false for the far-edge full-fill entry (lower-probability, requires the entire gap to be filled first)
Returns: the entry price, or na if z.kind isn't a recognized FVG type
파인 라이브러리
트레이딩뷰의 진정한 정신에 따라, 작성자는 이 파인 코드를 오픈소스 라이브러리로 게시하여 커뮤니티의 다른 파인 프로그래머들이 재사용할 수 있도록 했습니다. 작성자에게 경의를 표합니다! 이 라이브러리는 개인적으로 사용하거나 다른 오픈소스 게시물에서 사용할 수 있지만, 이 코드의 게시물 내 재사용은 하우스 룰에 따라 규제됩니다.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
파인 라이브러리
트레이딩뷰의 진정한 정신에 따라, 작성자는 이 파인 코드를 오픈소스 라이브러리로 게시하여 커뮤니티의 다른 파인 프로그래머들이 재사용할 수 있도록 했습니다. 작성자에게 경의를 표합니다! 이 라이브러리는 개인적으로 사용하거나 다른 오픈소스 게시물에서 사용할 수 있지만, 이 코드의 게시물 내 재사용은 하우스 룰에 따라 규제됩니다.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.