Bibliothèque

CatalystCalendarDataData component of the Catalyst economic calendar indicator.
WHAT THIS CONTAINS
A compiled release schedule for economic and commodity events across US, Euro
Area, UK, Japan, Australia, New Zealand, Canada, Switzerland and China, plus
energy and agricultural reports, Treasury auctions and market-structure dates.
Roughly 24 months of history and 12 months of forward schedule.
The schedule is compiled offline from official agency calendars: the Federal
Reserve, FRED, the US Bureau of Labor Statistics, the US Energy Information
Administration, and the published policy meeting calendars of the ECB, Bank of
England, Bank of Canada, Reserve Bank of Australia, Reserve Bank of New Zealand,
Bank of Japan and Swiss National Bank.
This library holds dates only. Released values are read separately through
request.economic().
EXPORTS
monthChunk(year, month) the encoded occurrence records for one UTC month
keyTable() event metadata, one record per line
buildStamp() UTC milliseconds at which this data was generated
horizon() the first and last timestamp covered
FORMAT
Each occurrence is a fixed-width 10-character record, DDHHMMKKKI. The encoding is
documented inline in the source in enough detail to decode a record by hand.
UPDATE CADENCE
Regenerated and republished quarterly. Scripts pin a version number, so an
existing import keeps working until it is deliberately updated.
``` Bibliothèque

CryptonianEWFibLibrary "CryptonianEWFib"
Cryptonian Elliott Wave Fib /1. Stage-aware Fibonacci model, corrective projection geometry and Fresh-FVG lifecycle/confluence. Extracted from the proven 11.8c/11.8d host without methodology changes.
evaluate(goldProfile, ticker, chartTimeframeSeconds, fvgMinAtr, fvgMaxAgeBars, fibEngineOn, fvgEngineOn, fvgRequireSourceLeg, maxStoredFvgs, fvgMinRemainingPct, atrValue, mintick, currentBar, currentHigh, currentLow, currentClose, p0, p1, p2, p3, p4, pb0, pb1, pb2, pb3, primaryKey, primaryLockedCount, primaryDirection, primaryW2Depth, primaryW3Extension, primaryW4Depth, primaryW5Ratio, primaryQuality, correctionSourceKey, correctionCommittedCount, correctionOriginPrice, correctionSourceDirection, c1, cp1, c2, cp2, cb2, correctionConfirmed, correctionHasProvisional, fvgOriginalTops, fvgOriginalBottoms, fvgLiveTops, fvgLiveBottoms, fvgDirections, fvgBirthBars)
Parameters:
goldProfile (bool)
ticker (string)
chartTimeframeSeconds (int)
fvgMinAtr (float)
fvgMaxAgeBars (int)
fibEngineOn (bool)
fvgEngineOn (bool)
fvgRequireSourceLeg (bool)
maxStoredFvgs (int)
fvgMinRemainingPct (float)
atrValue (float)
mintick (float)
currentBar (int)
currentHigh (float)
currentLow (float)
currentClose (float)
p0 (float)
p1 (float)
p2 (float)
p3 (float)
p4 (float)
pb0 (int)
pb1 (int)
pb2 (int)
pb3 (int)
primaryKey (string)
primaryLockedCount (int)
primaryDirection (int)
primaryW2Depth (float)
primaryW3Extension (float)
primaryW4Depth (float)
primaryW5Ratio (float)
primaryQuality (float)
correctionSourceKey (string)
correctionCommittedCount (int)
correctionOriginPrice (float)
correctionSourceDirection (int)
c1 (float)
cp1 (bool)
c2 (float)
cp2 (bool)
cb2 (int)
correctionConfirmed (bool)
correctionHasProvisional (bool)
fvgOriginalTops (array)
fvgOriginalBottoms (array)
fvgLiveTops (array)
fvgLiveBottoms (array)
fvgDirections (array)
fvgBirthBars (array) Bibliothèque

CryptonianEWViewLibrary "CryptonianEWView"
Cryptonian Elliott Wave View /1. Dedicated presentation-policy layer for Minimal Trader, Balanced, Full Audit and Custom chart modes. Presentation only; no Elliott, Forecast, Trade, Runtime or Audit methodology.
resolve(mode, cleanChart, primaryDegreeLinesOn, secondaryDegreeLinesOn, subSecondaryDegreeLinesOn, alternateCountLinesOn, correctionLinesOn, showPivotSkeleton, showElliottChannels, showPrimaryCount, secondaryDegreeLabelsOn, subSecondaryDegreeLabelsOn, showAlternateCount, showCorrection, showPivotIds, showDevelopingPivot, showCorrectionLevels, showFibModel, showFreshFvg, showInvalidationLevel, showInvalidationTags, showRevisionTags, showTradeLevels, showTradeSignals, showPotentialForecast, forecastAuditOn, forecastAuditLabelsOn, contextForecastRoadmapOn, contextForecastMainLabelOn, contextForecastTargetLabelsOn, htfTradeBridgeGeometryOn, maxTradeLifecycleLabels)
Parameters:
mode (string)
cleanChart (bool)
primaryDegreeLinesOn (bool)
secondaryDegreeLinesOn (bool)
subSecondaryDegreeLinesOn (bool)
alternateCountLinesOn (bool)
correctionLinesOn (bool)
showPivotSkeleton (bool)
showElliottChannels (bool)
showPrimaryCount (bool)
secondaryDegreeLabelsOn (bool)
subSecondaryDegreeLabelsOn (bool)
showAlternateCount (bool)
showCorrection (bool)
showPivotIds (bool)
showDevelopingPivot (bool)
showCorrectionLevels (bool)
showFibModel (bool)
showFreshFvg (bool)
showInvalidationLevel (bool)
showInvalidationTags (bool)
showRevisionTags (bool)
showTradeLevels (bool)
showTradeSignals (bool)
showPotentialForecast (bool)
forecastAuditOn (bool)
forecastAuditLabelsOn (bool)
contextForecastRoadmapOn (bool)
contextForecastMainLabelOn (bool)
contextForecastTargetLabelsOn (bool)
htfTradeBridgeGeometryOn (bool)
maxTradeLifecycleLabels (int)
drawActiveZone(boxStore, labelStore, enabled, startBar, projectionBars, zoneTop, zoneBottom, zoneName, zoneColor, panelColor, labelSize)
Parameters:
boxStore (array)
labelStore (array)
enabled (bool)
startBar (int)
projectionBars (int)
zoneTop (float)
zoneBottom (float)
zoneName (string)
zoneColor (color)
panelColor (color)
labelSize (string) Bibliothèque

CryptonianEWAuditLibrary "CryptonianEWAudit"
Cryptonian Elliott Wave Audit /1. Owns production integrity auditing, compact event-state construction, universal-event aggregation and alert deduplication for the library-first Elliott architecture. The audit rules are migrated from Elliott Wave Engine 11.8b2 without changing Elliott or trade methodology.
addUniqueLimited(values, value, maximumSize)
Adds one unique string and caps the registry size.
Parameters:
values (array)
value (string)
maximumSize (int)
eventOnce(eventRegistry, eventCondition, eventName, sourceKey, maximumSize, deduplicate)
Generic event de-duplication helper. This preserves the 11.8b2 event
key contract: eventName | sourceKey | time.
Parameters:
eventRegistry (array)
eventCondition (bool)
eventName (string)
sourceKey (string)
maximumSize (int)
deduplicate (bool)
eventState(lastEvent, currentCountKey, lastInvalidCountKey, forecastKey, tradeId, countStarted, countRevised, countInvalidated, forecastNew, forecastRevised, forecastInvalidated, tradeWaiting, tradeActivated, tradeResolved, tradeCountInvalidExit)
Creates the shared Model.EventState. The code field is a bit-mask for
future audit/UI use; the named booleans remain the authoritative contract.
Parameters:
lastEvent (string)
currentCountKey (string)
lastInvalidCountKey (string)
forecastKey (string)
tradeId (string)
countStarted (bool)
countRevised (bool)
countInvalidated (bool)
forecastNew (bool)
forecastRevised (bool)
forecastInvalidated (bool)
tradeWaiting (bool)
tradeActivated (bool)
tradeResolved (bool)
tradeCountInvalidExit (bool)
tradeLifecycleEvent(resolution)
True when Trade's per-bar resolution contains any lifecycle event.
TP1 is intentionally included even when the trade remains live because 11.8b2
treats TP1 as an alert-worthy lifecycle event.
Parameters:
resolution (TradeResolution type from AYEHAN/CryptonianEWModel/1)
productionAudit(pivotPrices, pivotBars, pivotTimes, pivotTypes, pivotIds, nestedPivotPrices, nestedPivotTimes, fvgOriginalTops, fvgOriginalBottoms, fvgLiveTops, fvgLiveBottoms, fvgDirections, fvgBirthBars, tradeActivationCount, tradeResolutionCount, tradeProfitableResolutions, tradeLosingResolutions, tradeFlatResolutions, tradeCancelled, tradeWaitingCancellationCount, tradeTp1ReachedCount, tradeTp2ReachedCount, tradeLive, tradeSetupId, tradeDirection, tradeEntry, tradeStop, tradeTp1)
Runs the original 11.8b2 production audit and owns persistent issue
history internally. Call this once per host bar.
Parameters:
pivotPrices (array)
pivotBars (array)
pivotTimes (array)
pivotTypes (array)
pivotIds (array)
nestedPivotPrices (array)
nestedPivotTimes (array)
fvgOriginalTops (array)
fvgOriginalBottoms (array)
fvgLiveTops (array)
fvgLiveBottoms (array)
fvgDirections (array)
fvgBirthBars (array)
tradeActivationCount (int)
tradeResolutionCount (int)
tradeProfitableResolutions (int)
tradeLosingResolutions (int)
tradeFlatResolutions (int)
tradeCancelled (int)
tradeWaitingCancellationCount (int)
tradeTp1ReachedCount (int)
tradeTp2ReachedCount (int)
tradeLive (bool)
tradeSetupId (string)
tradeDirection (int)
tradeEntry (float)
tradeStop (float)
tradeTp1 (float)
universalEventRaw(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow)
Reproduces the 11.8b2 universal-event OR tree using the compact shared
EventState plus the few event families not represented by Model /1.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
universalAlert(rawEvent, maximumSize, deduplicate)
Stateful universal alert. The registry lives in Audit /1 rather than
the indicator host. This preserves 11.8b2's ANY_EW_EVENT | bar_index | time key.
Call once per host bar, then feed .fire to the single alertcondition().
Parameters:
rawEvent (bool)
maximumSize (int)
deduplicate (bool)
processUniversalAlert(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow, maximumSize, deduplicate)
Convenience wrapper: aggregate + deduplicate in one host call.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
maximumSize (int)
deduplicate (bool)
ProductionAuditState
Complete production-integrity result. Individual checks are retained so
Fields:
pass (series bool)
status (series string)
currentIssue (series string)
signature (series string)
unresolvedActivations (series int)
issueCount (series int)
lastIssue (series string)
changedNow (series bool)
pivotArraysAligned (series bool)
nestedArraysAligned (series bool)
fvgArraysAligned (series bool)
tradeAccounting (series bool)
tradeResultAccounting (series bool)
cancellationAccounting (series bool)
liveIdentity (series bool)
liveOrdering (series bool)
tp1Accounting (series bool)
UniversalEventState
Compact result from the universal Elliott event aggregator.
Fields:
raw (series bool)
fire (series bool)
key (series string) Bibliothèque

CryptonianEWRuntimeLibrary "CryptonianEWRuntime"
Cryptonian Elliott Wave Runtime /1. Owns adaptive MTF profile selection, compact context/bridge request expressions, lower-timeframe confirmation processing, MTF trade gates, bottom-up bootstrap assembly, Context EW forecast assembly, HTF trade-bridge request expressions, nested-pivot request expressions, production gates and final engine-state packing. Methodology is preserved from Elliott Wave Engine 11.8b2; this library is an architecture migration, not a rules rewrite.
autoContextTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
autoConfirmationTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
autoBridgeTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
profileState(enabled, autoProfile, manualContextTimeframe, manualExecutionTimeframe, manualConfirmationTimeframe, chartTimeframe, chartSeconds)
Builds the timeframe/profile portion of Model.MtfState.
It deliberately does not perform any data request.
Parameters:
enabled (bool)
autoProfile (bool)
manualContextTimeframe (string)
manualExecutionTimeframe (string)
manualConfirmationTimeframe (string)
chartTimeframe (string)
chartSeconds (int)
bridgeTimeframe(autoProfile, manualConfirmationTimeframe, chartSeconds)
Returns the active lower bridge timeframe used by the existing
bottom-up Elliott bootstrap. This remains separate because Model /1 MtfState
intentionally stores only Context / Execution / Confirmation.
Parameters:
autoProfile (bool)
manualConfirmationTimeframe (string)
chartSeconds (int)
bridgeTimeframeValid(bridgeTf, chartSeconds)
Parameters:
bridgeTf (string)
chartSeconds (int)
contextPack(mtfPivotStrength, atrLength, mtfMinimumSwingAtr, allowDiagonals, allowTruncation, truncationMinimumPct, contextPivotStrength, contextMinimumSwingAtr, candidateStarts, minimumNewCandidateScore, extensionThreshold, diagonalTolerance, invalidationMode)
Exact 11.8b2 higher-timeframe context packet.
mtfConfirmedSnapshot() retains the old trade-context methodology while
contextConfirmedSnapshot() retains the separate Context-EW forecast geometry.
Parameters:
mtfPivotStrength (int)
atrLength (simple int)
mtfMinimumSwingAtr (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
contextPivotStrength (int)
contextMinimumSwingAtr (float)
candidateStarts (int)
minimumNewCandidateScore (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
mtfContextState(pack)
Converts ContextPack's MTF branch into the shared DegreeState contract.
Parameters:
pack (ContextPack)
contextForecastDegreeState(pack)
Converts ContextPack's full Context-EW branch into DegreeState.
Parameters:
pack (ContextPack)
bridgeDegreeState(pivotStrength, atrLength, minimumSwingAtr, candidateStarts, minimumNewScore, allowDiagonals, allowTruncation, truncationMinimumPct, extensionThreshold, diagonalTolerance, invalidationMode)
Exact lower-bridge structural expression, object form.
Parameters:
pivotStrength (int)
atrLength (simple int)
minimumSwingAtr (float)
candidateStarts (int)
minimumNewScore (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
ltfMomentumSignal(fastLength, slowLength)
Exact lower-timeframe momentum expression used by 11.8b2.
Parameters:
fastLength (simple int)
slowLength (simple int)
nestedPivotEvent(strength, atrLength)
Exact Part 9.2 lower-degree confirmed pivot event expression.
Parameters:
strength (int)
atrLength (simple int)
htfTradeBridgeState(enabled, degreeEngineOn, secondaryEnabled, subSecondaryEnabled, primaryPivotStrength, secondaryPivotStrength, subSecondaryPivotStrength, atrLength, primaryMinimumSwingAtr, secondaryMinimumSwingAtr, subSecondaryMinimumSwingAtr, candidateStarts, minimumNewScore, allowDiagonals, allowTruncation, truncationMinimumPct, extensionThreshold, diagonalTolerance, invalidationMode, minimumModelScore, stopBufferAtr)
Native HTF trade bridge request expression. Candidate discovery,
first-seen geometry freezing and W2/W3/W4/W5 classification remain in Trade /13.
Parameters:
enabled (bool)
degreeEngineOn (bool)
secondaryEnabled (bool)
subSecondaryEnabled (bool)
primaryPivotStrength (int)
secondaryPivotStrength (int)
subSecondaryPivotStrength (int)
atrLength (simple int)
primaryMinimumSwingAtr (float)
secondaryMinimumSwingAtr (float)
subSecondaryMinimumSwingAtr (float)
candidateStarts (int)
minimumNewScore (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
minimumModelScore (float)
stopBufferAtr (float)
updateMtfState(previous, enabled, autoProfile, manualContextTimeframe, manualExecutionTimeframe, manualConfirmationTimeframe, chartTimeframe, chartSeconds, gateMode, requireExecutionTimeframe, ltfConfirmationMaximumAge, realtimeBar, context, ltfSignalValues, ltfSignalTimes, primaryDirection, correctionDirection)
Updates one persistent Model.MtfState object from the current profile,
requested context packet and request.security_lower_tf() signal/time arrays.
Pass a persistent initialized object from the host, then assign the returned object
back to it on every bar. The function intentionally ignores the realtime chart
bar's final LTF intrabar, exactly as 11.8b2 did.
Parameters:
previous (MtfState type from AYEHAN/CryptonianEWModel/1)
enabled (bool)
autoProfile (bool)
manualContextTimeframe (string)
manualExecutionTimeframe (string)
manualConfirmationTimeframe (string)
chartTimeframe (string)
chartSeconds (int)
gateMode (string)
requireExecutionTimeframe (bool)
ltfConfirmationMaximumAge (int)
realtimeBar (bool)
context (ContextPack)
ltfSignalValues (array)
ltfSignalTimes (array)
primaryDirection (int)
correctionDirection (int)
runtimeEvents(current, previous, primaryDirection, correctionDirection)
Small event helper that replaces host history expressions with object
history applied correctly by the caller: pass current and previous Runtime states.
Parameters:
current (MtfState type from AYEHAN/CryptonianEWModel/1)
previous (MtfState type from AYEHAN/CryptonianEWModel/1)
primaryDirection (int)
correctionDirection (int)
bootstrapState(chartPrimaryMissing, bridge, context, chartClose, chartAtr)
Parameters:
chartPrimaryMissing (bool)
bridge (DegreeState type from AYEHAN/CryptonianEWModel/1)
context (DegreeState type from AYEHAN/CryptonianEWModel/1)
chartClose (float)
chartAtr (float)
contextForecastState(enabled, contextTimeframeValid, context, armScore)
Parameters:
enabled (bool)
contextTimeframeValid (bool)
context (ContextPack)
armScore (float)
processNested(eventTypes, eventPrices, eventTimes, eventAtrs, barTimes, pivotPrices, pivotTimes, pendingType, pendingPrice, pendingTime, pendingAtr, lastEventTime, coverageStartTime, coverageEndTime, minimumSwingAtr, enabled)
Parameters:
eventTypes (array)
eventPrices (array)
eventTimes (array)
eventAtrs (array)
barTimes (array)
pivotPrices (array)
pivotTimes (array)
pendingType (int)
pendingPrice (float)
pendingTime (int)
pendingAtr (float)
lastEventTime (int)
coverageStartTime (int)
coverageEndTime (int)
minimumSwingAtr (float)
enabled (bool)
nestedLeg(pivotPrices, pivotTimes, coverageStartTime, coverageEndTime, engineOn, timeframeValid, t0, y0, t1, y1, direction, motive, diagonal, confirmed)
Parameters:
pivotPrices (array)
pivotTimes (array)
coverageStartTime (int)
coverageEndTime (int)
engineOn (bool)
timeframeValid (bool)
t0 (int)
y0 (float)
t1 (int)
y1 (float)
direction (int)
motive (bool)
diagonal (bool)
confirmed (bool)
structuralProductionGate(productionMode, confirmOnClose, barConfirmed)
Parameters:
productionMode (bool)
confirmOnClose (bool)
barConfirmed (bool)
tradeActivationProductionGate(productionMode, confirmOnClose, barConfirmed)
Parameters:
productionMode (bool)
confirmOnClose (bool)
barConfirmed (bool)
packEngineState(primary, secondary, subSecondary, correction, bootstrap, parent, degreeResolution, forecast, contextForecast, mtf, htfTrade, events)
Parameters:
primary (DegreeState type from AYEHAN/CryptonianEWModel/1)
secondary (DegreeState type from AYEHAN/CryptonianEWModel/1)
subSecondary (DegreeState type from AYEHAN/CryptonianEWModel/1)
correction (CorrectionState type from AYEHAN/CryptonianEWModel/1)
bootstrap (BootstrapState type from AYEHAN/CryptonianEWModel/1)
parent (ParentHypothesis type from AYEHAN/CryptonianEWModel/1)
degreeResolution (DegreeResolutionState type from AYEHAN/CryptonianEWModel/1)
forecast (ForecastState type from AYEHAN/CryptonianEWModel/1)
contextForecast (ContextForecastState type from AYEHAN/CryptonianEWModel/1)
mtf (MtfState type from AYEHAN/CryptonianEWModel/1)
htfTrade (TradeBridgePack type from AYEHAN/CryptonianEWModel/1)
events (EventState type from AYEHAN/CryptonianEWModel/1)
ContextPack
One request-safe higher-timeframe packet containing both legacy MTF
Fields:
mtfDirection (series int)
mtfStage (series int)
mtfQuality (series float)
mtfInvalidation (series float)
mtfDiagonal (series bool)
forecastDirection (series int)
forecastStage (series int)
forecastScore (series float)
forecastInvalidation (series float)
forecastDiagonal (series bool)
p0 (series float)
p1 (series float)
p2 (series float)
p3 (series float)
p4 (series float)
p5 (series float)
confirmedClose (series float)
RuntimeEvents
Small host-facing diagnostic packet for runtime transitions.
Fields:
contextChanged (series bool)
motiveGateReady (series bool)
correctionGateReady (series bool) Bibliothèque

Bibliothèque

OMSF_Education_LibTo keep the codebase of the OMSF Learning Space indicator cleanly structured, easy to read, and as concise as possible, I have extracted core calculations and logic functions into this reusable library. This keeps the main script lightweight while allowing you to flexibly utilize these individual building blocks for your own custom scripts and quantitative experiments.
Extracted Functions & Modules
1. pivot_fun – Pivot Analytics & Trend State
Derivatives of the classic Pivot High/Low concept to identify key structural highs and lows using configurable confirmation lookback windows.
Provides continuously updated persistent pivot levels, running extreme levels, and a clean trend state machine (1 = Long, -1 = Short) along with standard pivot lag metrics (avg_std_delay).
2. dir_kaufman_eff_ratio – Directional Kaufman Efficiency Ratio (KER)
Computes directional trend efficiency ranging from -1.0 (strong downward efficiency) to +1.0 (strong upward efficiency), featuring built-in protection against division by zero.
3. ker_marketstructure_validation – KER Market Structure Validation
Accumulates and averages KER metrics separately for Long and Short market regimes to evaluate overall structural trend quality.
4. max_excurs_ratio – MFE / MAE Analytics
Tracks ATR-normalized Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) values for individual trend segments.
Computes running aggregate ratios and stores historical trade metrics in float arrays—ideal for statistical distribution and percentile analysis.
5. vis_mfe_mae_ratio_long & vis_mfe_mae_ratio_short – Visualization Components
Renders dynamic chart overlays featuring break-even levels, stop-loss excursion bounds, color fills, and informational labels displaying real-time or locked segment performance.
📌 Coming next:
OMSF Learning Space Update: Chapter 5 MFE/MAE. ()
Best regards, arni Bibliothèque

XZ_Research_UtilitiesLibrary "XZ_Research_Utilities"
Generic descriptive-statistics and two-column research-table utilities. Contains no XZ trading methodology or analytical authority.
resolvePosition(key)
Resolves a normalized table-position key.
Parameters:
key (string) : Position key.
Returns: Pine table position constant.
resolveTextSize(key)
Resolves a normalized text-size key.
Parameters:
key (string) : Size key.
Returns: Pine size constant.
countEqual(values, target)
Counts values equal to a target.
Parameters:
values (array) : Integer observations.
target (int) : Target value.
Returns: Matching observation count.
countPositive(values)
Counts values greater than zero.
Parameters:
values (array) : Integer observations.
Returns: Positive observation count.
countAtLeast(values, threshold)
Counts values at or above a threshold.
Parameters:
values (array) : Integer observations.
threshold (int) : Inclusive threshold.
Returns: Observation count at/above threshold.
sumInt(values)
Sums integer observations.
Parameters:
values (array) : Integer observations.
Returns: Sum.
selectedStat(values, mode)
Returns Median or Mean from float observations.
Parameters:
values (array) : Float observations.
mode (string) : "Median" or "Mean".
Returns: Selected descriptive statistic or na for an empty sample.
number(value, suffix)
Formats a numeric result with an optional suffix.
Parameters:
value (float) : Numeric result.
suffix (string) : Suffix such as d or %.
Returns: Formatted number or em dash for na.
percent(numerator, denominator)
Formats numerator/denominator as a percentage.
Parameters:
numerator (int) : Numerator.
denominator (int) : Denominator.
Returns: Percentage or em dash when denominator is zero.
createTable(positionKey, rows, backgroundColor, lineColor, showLines)
Creates a two-column research table.
Parameters:
positionKey (string) : Normalized table-position key.
rows (int) : Row count.
backgroundColor (color) : Background colour.
lineColor (color) : Frame/border colour.
showLines (bool) : Whether frame and borders are visible.
Returns: Table handle.
header(id, leftText, rightText, accentColor, textColor, backgroundColor, textSize, leftTooltip, rightTooltip)
Writes the two-column research header.
Parameters:
id (table) : Table handle.
leftText (string) : Left header text.
rightText (string) : Right header text.
accentColor (color) : Accent colour.
textColor (color) : Neutral text colour.
backgroundColor (color) : Shared background.
textSize (string) : Normalized text-size key.
leftTooltip (string) : Left-cell tooltip.
rightTooltip (string) : Right-cell tooltip.
Returns: True after rendering.
row(id, row, labelText, valueText, textColor, accentColor, backgroundColor, textSize, tooltipText, accentValue)
Writes one label/value research row.
Parameters:
id (table) : Table handle.
row (int) : Row index.
labelText (string) : Left label.
valueText (string) : Right value.
textColor (color) : Neutral text colour.
accentColor (color) : Optional emphasized value colour.
backgroundColor (color) : Shared background.
textSize (string) : Normalized text-size key.
tooltipText (string) : Shared metric-definition tooltip.
accentValue (bool) : Whether the right value uses accent colour.
Returns: True after rendering. Bibliothèque

XZ_Table_PrimitivesLibrary "XZ_Table_Primitives"
Generic Pine table construction and cell-rendering primitives for XZ scripts. Contains no trading methodology or analytical authority.
resolvePosition(key)
Resolves a normalized position key to a Pine table position.
Parameters:
key (string) : Position key: top_left, top_center, top_right, middle_left, middle_center, middle_right, bottom_left, bottom_center or bottom_right.
Returns: Pine position constant.
resolveTextSize(key)
Resolves a normalized text-size key to a Pine size constant.
Parameters:
key (string) : Text-size key: tiny, small, normal, large or huge.
Returns: Pine size constant.
create(positionKey, columns, rows, backgroundColor, frameColor, frameWidth)
Creates a table using caller-supplied presentation values.
Parameters:
positionKey (string) : Normalized table position key.
columns (int) : Number of columns.
rows (int) : Number of rows.
backgroundColor (color) : Table background color.
frameColor (color) : Table frame color.
frameWidth (int) : Table frame width.
Returns: New table handle.
clearRegion(id, firstColumn, firstRow, lastColumn, lastRow)
Clears a rectangular region of an existing table.
Parameters:
id (table) : Table handle.
firstColumn (int) : First column index.
firstRow (int) : First row index.
lastColumn (int) : Last column index.
lastRow (int) : Last row index.
Returns: True after clearing.
cell(id, column, row, cellText, textColor, backgroundColor, textSize, horizontalAlign, tooltipText)
Writes one fully specified table cell.
Parameters:
id (table) : Table handle.
column (int) : Column index.
row (int) : Row index.
cellText (string) : Cell text.
textColor (color) : Text color.
backgroundColor (color) : Cell background color.
textSize (string) : Pine text size constant.
horizontalAlign (string) : Pine text alignment constant.
tooltipText (string) : Cell tooltip text.
Returns: True after writing.
twoColumnRow(id, row, labelText, valueText, labelColor, valueColor, backgroundColor, textSize, labelTooltip, valueTooltip)
Writes one two-column label/value row.
Parameters:
id (table) : Table handle.
row (int) : Row index.
labelText (string) : Left-cell text.
valueText (string) : Right-cell text.
labelColor (color) : Left text color.
valueColor (color) : Right text color.
backgroundColor (color) : Shared cell background color.
textSize (string) : Shared Pine text size constant.
labelTooltip (string) : Left-cell tooltip.
valueTooltip (string) : Right-cell tooltip.
Returns: True after writing both cells.
twoColumnHeader(id, row, leftText, rightText, leftColor, rightColor, backgroundColor, textSize, leftTooltip, rightTooltip)
Writes one two-column header/decoder row.
Parameters:
id (table) : Table handle.
row (int) : Row index.
leftText (string) : Left-cell text.
rightText (string) : Right-cell text.
leftColor (color) : Left text color.
rightColor (color) : Right text color.
backgroundColor (color) : Shared background color.
textSize (string) : Shared Pine text size constant.
leftTooltip (string) : Left-cell tooltip.
rightTooltip (string) : Right-cell tooltip.
Returns: True after writing both cells.
mergedSection(id, row, firstColumn, lastColumn, sectionText, textColor, backgroundColor, textSize, tooltipText)
Writes one merged full-width section row.
Parameters:
id (table) : Table handle.
row (int) : Row index.
firstColumn (int) : First column to merge.
lastColumn (int) : Last column to merge.
sectionText (string) : Section text.
textColor (color) : Text color.
backgroundColor (color) : Cell background color.
textSize (string) : Pine text size constant.
tooltipText (string) : Cell tooltip.
Returns: True after writing and merging. Bibliothèque

XZ_Display_PrimitivesLibrary "XZ_Display_Primitives"
Generic bar-time drawing primitives for Pine scripts. Creates, updates or deletes lines, labels and boxes from caller-supplied presentation facts. Contains no trading methodology or analytical authority.
horizontalLine(id, visible, leftTime, rightTime, price, extendRight, lineColor, lineStyle, lineWidth)
Creates, updates or deletes one horizontal bar-time line.
Parameters:
id (line) : Existing line handle, or na.
visible (bool) : Whether the line should exist.
leftTime (int) : Left endpoint time.
rightTime (int) : Right endpoint time used when the line is finite and as the current anchor when projected.
price (float) : Horizontal price.
extendRight (bool) : True to project with extend.right, false for a finite segment.
lineColor (color) : Line color.
lineStyle (string) : Pine line style.
lineWidth (int) : Line width.
Returns: Updated line handle, or na when hidden/invalid.
segmentLine(id, visible, firstTime, firstPrice, secondTime, secondPrice, lineColor, lineStyle, lineWidth)
Creates, updates or deletes one finite bar-time line segment.
Parameters:
id (line) : Existing line handle, or na.
visible (bool) : Whether the line should exist.
firstTime (int) : First endpoint time.
firstPrice (float) : First endpoint price.
secondTime (int) : Second endpoint time.
secondPrice (float) : Second endpoint price.
lineColor (color) : Line color.
lineStyle (string) : Pine line style.
lineWidth (int) : Line width.
Returns: Updated line handle, or na when hidden/invalid.
priceLabel(id, visible, xTime, price, labelText, textColor, backgroundColor, labelStyle, labelSize, tooltipText, textAlign)
Creates, updates or deletes one price-anchored bar-time label.
Parameters:
id (label) : Existing label handle, or na.
visible (bool) : Whether the label should exist.
xTime (int) : Label time coordinate.
price (float) : Label price coordinate.
labelText (string) : Visible label text.
textColor (color) : Label text color.
backgroundColor (color) : Label background color.
labelStyle (string) : Pine label style.
labelSize (string) : Pine label size.
tooltipText (string) : Tooltip text.
textAlign (string) : Pine text alignment.
Returns: Updated label handle, or na when hidden/invalid.
timeBox(id, visible, leftTime, rightTime, top, bottom, extendRight, fillColor, borderColor, borderStyle, borderWidth)
Creates, updates or deletes one bar-time box.
Parameters:
id (box) : Existing box handle, or na.
visible (bool) : Whether the box should exist.
leftTime (int) : Left box time.
rightTime (int) : Right box time used when finite and as the current anchor when projected.
top (float) : Top price.
bottom (float) : Bottom price.
extendRight (bool) : True to project with extend.right, false for finite geometry.
fillColor (color) : Box fill color. May be na.
borderColor (color) : Box border color. May be na.
borderStyle (string) : Pine line style for the border.
borderWidth (int) : Border width.
Returns: Updated box handle, or na when hidden/invalid.
setBoxColors(id, fillColor, borderColor)
Applies fill and border colors to an existing box without changing geometry.
Parameters:
id (box) : Box handle.
fillColor (color) : New fill color.
borderColor (color) : New border color.
Returns: True after the no-op or update.
setBoxBorderColor(id, borderColor)
Applies only a border color to an existing box without changing geometry.
Parameters:
id (box) : Box handle.
borderColor (color) : New border color.
Returns: True after the no-op or update.
setLabelTextColor(id, textColor)
Applies text color to an existing label without changing its geometry or text.
Parameters:
id (label) : Label handle.
textColor (color) : New text color.
Returns: True after the no-op or update.
clearBoxText(id)
Clears box text without changing geometry or styling.
Parameters:
id (box) : Box handle.
Returns: True after the no-op or update. Bibliothèque

XZ_Core_UtilitiesLibrary "XZ_Core_Utilities"
Generic formatting, identifier parsing and neutral geometry helpers for XZ scripts. Contains no XZ methodology or analytical authority.
csvContainsPositiveInt(objectId, csvIds)
Returns true when a positive integer ID occurs as a comma-separated token.
Parameters:
objectId (int) : Positive integer to search for.
csvIds (string) : Comma-separated integer text. Spaces are ignored.
Returns: True when objectId occurs as an exact parsed token.
csvFirstPositiveInt(csvIds)
Returns the first positive integer token in comma-separated text.
Parameters:
csvIds (string) : Comma-separated integer text. Spaces are ignored.
Returns: First parsed positive integer, or 0 when none exists.
nearDuplicateBounds(lowA, highA, lowB, highB, tolerancePct)
Tests whether two low/high geometries are near-duplicates under a supplied percentage tolerance.
Parameters:
lowA (float) : First lower bound.
highA (float) : First upper bound.
lowB (float) : Second lower bound.
highB (float) : Second upper bound.
tolerancePct (float) : Tolerance as a percentage of the wider geometry.
Returns: True when both corresponding boundaries fall within the calculated tolerance.
formatDate(eventTime, timezone)
Formats a timestamp as yyyy-MM-dd in the supplied timezone.
Parameters:
eventTime (int) : UNIX timestamp in milliseconds.
timezone (string) : Timezone string accepted by str.format_time().
Returns: Formatted date, or an em dash for na.
formatPercent(value)
Formats a percentage value with up to two decimals.
Parameters:
value (float) : Percentage value.
Returns: Percentage text, or an em dash for na.
formatSignedPercent(value)
Formats a signed percentage value with up to two decimals.
Parameters:
value (float) : Percentage value.
Returns: Signed percentage text, or an em dash for na.
timeframeLabel(tf)
Converts common TradingView timeframe strings into compact readable labels.
Parameters:
tf (string) : TradingView timeframe string.
Returns: Compact label such as 1D, 1W, 4H or 15m.
formatDistance(distance, useTicks, minTick)
Formats an absolute price distance as points or ticks. Unit policy is supplied by the caller.
Parameters:
distance (float) : Raw price distance.
useTicks (bool) : True to convert distance to ticks.
minTick (float) : Instrument minimum tick.
Returns: Formatted absolute distance with explicit unit.
directionalMovePct(fromPrice, toPrice, minTick)
Calculates signed percentage move from one price to another.
Parameters:
fromPrice (float) : Chronological starting price.
toPrice (float) : Chronological ending price.
minTick (float) : Instrument minimum tick used to reject a near-zero denominator.
Returns: Signed percentage move, or na when unavailable.
normalizedPositionPct(currentValue, lowPrice, highPrice)
Calculates normalized position of a value within low-to-high geometry.
Parameters:
currentValue (float) : Value being located.
lowPrice (float) : Geometry lower bound.
highPrice (float) : Geometry upper bound.
Returns: Position percentage where 0 is the lower bound and 100 is the upper bound. Values may fall outside 0-100.
formatElapsedDays(fromTime, toTime)
Formats elapsed milliseconds between two timestamps as fractional days.
Parameters:
fromTime (int) : Starting timestamp.
toTime (int) : Ending timestamp.
Returns: Day text with singular/plural unit, or an em dash when invalid.
quartilePrice(low, high, levelIndex)
Returns one of five equally spaced 0/25/50/75/100 geometry levels.
Parameters:
low (float) : Lower geometry bound.
high (float) : Upper geometry bound.
levelIndex (int) : Integer level index from 0 to 4.
Returns: Price at the requested quartile level.
quartileText(levelIndex)
Returns the display text for quartile level index 0-4.
Parameters:
levelIndex (int) : Integer level index from 0 to 4.
Returns: 0%, 25%, 50%, 75% or 100%.
appendUniqueToken(current, token, separator)
Appends a token only when it is not already present in a separator-delimited string.
Parameters:
current (string) : Existing token string.
token (string) : Token to append.
separator (string) : Delimiter between tokens.
Returns: Original or extended token string. Bibliothèque

ZoneKitLibrary "ZoneKit"
Generic 3-candle price-gap zone detection and drawing utilities.
Detects a gap between two candle extremes separated by one middle
candle, with an optional stricter mode requiring displacement on
both sides of the gap. Builds a box (and optional midline) to
represent the zone once detected.
scanZone(mode, h0, h2, l0, l2, c0, c1, c2, o0, o1, o2, minGap)
Scans three consecutive candles for a price-gap zone in either
direction.
Parameters:
mode (string) : "Standard" for a plain 3-candle gap; "Confirmed" for a gap
that also requires displacement (an "outside print") on both
sides of the gap, a stricter variant.
h0 (float) : Current candle's high.
h2 (float) : Two candles back's high.
l0 (float) : Current candle's low.
l2 (float) : Two candles back's low.
c0 (float) : Current candle's close.
c1 (float) : One candle back's close.
c2 (float) : Two candles back's close.
o0 (float) : Current candle's open.
o1 (float) : One candle back's open.
o2 (float) : Two candles back's open.
minGap (float) : Minimum required gap size, in price units.
Returns:
buildZone(top, bot, formTime, confTime, hourEnd, isUp, isLast, zoneColor, showMid, midColor, midStyle)
Draws a zone box (and optional midline) and returns the
populated Zone object.
Parameters:
top (float) : The zone's upper boundary.
bot (float) : The zone's lower boundary.
formTime (int) : Bar time the zone formed.
confTime (int) : Bar time the zone was confirmed.
hourEnd (int) : Caller-defined expiry time for the zone.
isUp (bool) : True if this is an upward (bullish) zone.
isLast (bool) : Caller-defined flag, passed straight through to the Zone.
zoneColor (color) : The resolved color for the box (and border).
showMid (bool) : Whether to also draw a midline through the zone's center.
midColor (color) : Color for the midline, if drawn.
midStyle (string) : Line style for the midline: "Solid", "Dotted", or "Dashed".
Returns: The newly created Zone.
Zone
Represents a detected price-gap zone and its drawn chart objects.
Fields:
mainBox (series box) : The zone's drawn box.
midLine (series line) : Optional midline through the zone's center.
boxLabel (series label) : Optional label attached to the zone.
overlayBox (series box) : Optional secondary box (e.g. for partial-fill shading).
top (series float) : The zone's upper boundary.
bot (series float) : The zone's lower boundary.
formationTime (series int) : The bar time the zone formed.
confirmTime (series int) : The bar time the zone was confirmed.
hourEnd (series int) : A caller-defined expiry time for the zone.
isFilled (series bool) : Whether the zone has been fully filled/mitigated.
wasHit (series bool) : Whether price has touched the zone at all.
isProcessed (series bool) : Internal bookkeeping flag for caller use.
isLast (series bool) : Caller-defined flag (e.g. "most recent of its kind").
isBull (series bool) : True if the zone is an upward (bullish) gap.
isFlipped (series bool) : Whether the zone has flipped direction (price closed
fillProgress (series float) : Tracks how far into the zone price has intruded. Bibliothèque

FootprintKitAnalysis toolkit for the native footprint API introduced in Pine v6. It turns a `footprint` object into aggregated row statistics, price-interval measurements, low and high volume node runs, stacked imbalances, unfinished auction reads, absorption reads and multi-bar composite profiles.
It is written for script authors who build their own footprint tools and who would otherwise re-implement the same row loops in every script.
WHY THE LIBRARY NEVER CALLS request.footprint()
Pine allows only one unique footprint request per script. If the library issued that request internally it would consume the caller's single slot, and the importing script could no longer query the footprint on its own terms. So the caller makes the one allowed call and passes the resulting object into every function.
The consequence is that the library performs no requests, draws nothing and keeps no persistent state outside the Profile object you create yourself. There is nothing in it that can repaint.
WHAT IT COMPUTES THAT THE API DOES NOT EXPOSE
- Stacked imbalances. The API flags imbalance per row; the stack of consecutive flagged rows is what carries meaning in footprint reading, and it has to be assembled.
- Unfinished auction at the extremes of a bar, i.e. an extreme row that still shows trade on both sides.
- Volume traded inside an arbitrary price interval, with rows that only partly overlap the interval counted pro rata.
- Runs of thin rows, the price pockets a move passed through without trade, and runs of heavy rows, the shelves inside the bar.
- A composite profile across several bars with its own point of control and value area. request.footprint() returns one bar at a time; feeding successive bars into a Profile builds the multi-bar picture the single call cannot give.
- Distribution shape metrics that read the whole profile rather than only its peak.
FORMULAS
Aggressive volume per row and per interval is derived from total volume V and delta D as buy = (V + D) / 2 and sell = (V - D) / 2. This is exact by the definition of delta and avoids depending on optional per-row accessors.
slice() weights each row by the fraction of its height that falls inside the requested interval, k = overlap / rowHeight, clamped to 1. Counting a boundary row either whole or not at all is the usual source of error in hand-written versions.
concentration() is POC row volume divided by mean row volume. A value near 1 means volume was spread evenly, a high value means one price row absorbed most of the activity.
dispersion() is the Shannon entropy of the row volume distribution, normalised by ln(n) to the 0 to 1 range: H = -sum(p * ln p) / ln(n), where p is a row's share of bar volume. Zero means all volume sat in one row, one means a perfectly even spread. Unlike concentration it distinguishes a bar with two heavy rows from a bar with one.
deltaCentroid() returns the centre of mass of absolute delta as a fraction of the bar range from the low, showing where aggression concentrated regardless of which side was aggressive.
absorption() splits the bar range into thirds, measures each extreme third with slice(), and reports absorption when a third holds at least the requested share of bar volume while its delta points against the direction of the bar. Aggression that meets size and fails to move price is the signature of a passive participant taking the other side.
The composite value area grows outward from the point of control, repeatedly taking the heavier of the two neighbouring buckets until the requested share of total volume is enclosed.
USAGE
import Smart-Day-Trader/FootprintKit/1 as fpk
footprint fp = request.footprint(4, 70, 300)
fpk.RowStats s = fpk.stats(fp)
float conc = fpk.concentration(s)
float pos = fpk.pocPosition(s, high, low)
array voids = fpk.runs(fp, s, 0.4, 3, true)
= fpk.wicks(fp, open, high, low, close)
NOTES
A plan with footprint data access is required for the data itself; the library compiles on any plan because it makes no requests.
Choose ticks per row relative to the instrument's tick size rather than copying a default. On NASDAQ 100 E-mini futures the tick is 0.25 points, so 4 ticks per row equals one point and yields roughly 20 to 30 rows on a 5 minute bar. A value of 20 there would collapse the same bar into 4 rows, at which point concentration, entropy and row runs stop carrying information.
All functions accept a na footprint and return empty or na results rather than failing, so they are safe to call on bars without data.
REFERENCE
stats(fp)
Aggregates every row of a footprint in a single pass: totals, POC, delta,
imbalance counts and the price bounds actually covered by rows. Reading these values
one by one costs several loops over the same array; this does it once.
Parameters:
fp (footprint) : Footprint object returned by request.footprint(). Safe to pass na.
Returns: A RowStats object. When the footprint is na or empty, `n` is 0 and the
float fields are na.
concentration(s)
Concentration of the bar's volume: POC row volume divided by the mean row
volume. A value near 1 means volume was spread evenly across the bar; a high value
means a single price row absorbed most of the activity.
Parameters:
s (RowStats) : RowStats produced by stats().
Returns: The ratio, or na when statistics are empty.
dispersion(fp, s)
Normalised Shannon entropy of the volume distribution across rows, scaled to
0 to 1. Zero means all volume sat in one row, one means perfectly even spread. Unlike
concentration() this reads the whole shape rather than just the peak, so a bar with
two heavy rows is distinguished from a bar with one.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
Returns: Entropy in the 0 to 1 range, or na when fewer than two rows carry volume.
pocPosition(s, barHigh, barLow)
Where the POC sits inside the bar's range, as a fraction from the low.
0 places the heaviest row at the low of the bar, 1 at the high.
Parameters:
s (RowStats) : RowStats produced by stats().
barHigh (float) : High of the bar.
barLow (float) : Low of the bar.
Returns: Position clamped to 0 to 1, or na when the range is degenerate.
deltaCentroid(fp, barHigh, barLow)
Centre of mass of absolute delta inside the bar, as a fraction from the low.
Shows where aggression was concentrated regardless of which side was aggressive,
which often differs from where total volume sat.
Parameters:
fp (footprint) : Footprint object.
barHigh (float) : High of the bar.
barLow (float) : Low of the bar.
Returns: Position in the 0 to 1 range, or na when there is no delta to weight by.
slice(fp, priceA, priceB)
Volume traded inside an arbitrary price interval. Rows that only partly
overlap the interval are counted in proportion to the overlapped fraction of their
height, so the result is correct even when the interval boundaries fall mid-row.
This is the primitive behind wick, zone and level measurements.
Parameters:
fp (footprint) : Footprint object.
priceA (float) : One boundary of the interval. Order does not matter.
priceB (float) : The other boundary of the interval.
Returns: A Slice object. All fields are 0 and `share` is na when nothing overlaps.
wicks(fp, o, h, l, c)
Splits the bar's volume into upper wick, body and lower wick using slice(),
so partially overlapped rows are handled correctly. An empty upper wick slice on a
bar with a long upper shadow means price travelled there without trading size, which
reads very differently from a wick that carries volume.
Parameters:
fp (footprint) : Footprint object.
o (float) : Open of the bar.
h (float) : High of the bar.
l (float) : Low of the bar.
c (float) : Close of the bar.
Returns: A tuple of Slice objects.
runs(fp, s, ratio, minRun, below)
Finds every group of consecutive rows whose volume is below or above a
multiple of the bar's mean row volume, and returns them as price spans. With
below = true this locates thin rows, the price pockets a move passed through without
trade; with below = false it locates the heavy shelves inside the bar.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
ratio (float) : Multiplier applied to the mean row volume to form the threshold.
minRun (int) : Minimum number of consecutive rows required to report a span.
below (bool) : When true, keep rows at or below the threshold; when false, at or above.
Returns: An array of Span objects, ordered as the rows are ordered. Empty when nothing
qualifies.
stacks(fp, minRun, buySide)
Finds stacked imbalances: runs of consecutive rows all flagged on the same
side. The native API exposes the flag per row, but the stack is what carries meaning
in footprint reading, and stacks have to be assembled by hand.
Parameters:
fp (footprint) : Footprint object.
minRun (int) : Minimum number of consecutive flagged rows to report, commonly 3.
buySide (bool) : When true, collect buy imbalance stacks; when false, sell imbalance stacks.
Returns: An array of Span objects covering each stack. Empty when none reach minRun.
unfinished(fp, tol)
Tests the extreme rows for an unfinished auction: an extreme that still shows
trade on both sides, meaning the move stopped before either side was cleared out.
A finished extreme has one side at or near zero.
Parameters:
fp (footprint) : Footprint object.
tol (float) : Fraction of the extreme row's own volume below which a side counts as empty.
Use 0 for a strict test, or a small value such as 0.05 to tolerate noisy feeds.
Returns: A tuple of booleans. Both false when the footprint is empty.
absorption(fp, s, o, c, minShare)
Reads absorption at the extremes of the bar: one third of the bar's range
holding a large share of the volume with delta pointing against the bar's direction.
Aggression that meets size and fails to move price is the signature of a passive
participant taking the other side.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
o (float) : Open of the bar.
c (float) : Close of the bar.
minShare (float) : Minimum share of bar volume the third must hold, for example 0.4.
Returns: 1 when sellers were absorbed at the lows of an up bar, -1 when buyers were
absorbed at the highs of a down bar, 0 otherwise.
newProfile(step)
Creates an empty composite profile. request.footprint() delivers one bar at a
time; feeding successive bars into a profile builds the multi-bar picture the single
call cannot give on its own.
Parameters:
step (float) : Price bucket height. Use the row height from RowStats to keep the composite
at the same resolution as the footprint itself.
Returns: An empty Profile object.
method feed(p, fp)
Folds one bar's rows into the profile. Buckets are keyed by rounded row
midpoint and kept sorted, so repeated calls stay ordered and lookups stay cheap.
Call once per confirmed bar.
Namespace types: Profile
Parameters:
p (Profile) : Profile to update, modified in place.
fp (footprint) : Footprint object for the bar being added.
Returns: Nothing. The profile is mutated.
method sum(p)
Total volume held by the profile.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
Returns: Sum of all bucket volumes, or 0 when the profile is empty.
method poc(p)
Point of control of the composite profile.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
Returns: Centre price of the heaviest bucket, or na when the profile is empty.
method valueArea(p, pct)
Value area of the composite profile, grown outward from the point of control
by repeatedly taking the heavier neighbouring bucket until the requested share of
total volume is enclosed.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
pct (float) : Share of total volume to enclose, expressed 0 to 1, for example 0.7.
Returns: A tuple of prices, both na when the profile is empty.
method reset(p)
Empties the profile while keeping its bucket size, ready for a new window.
Namespace types: Profile
Parameters:
p (Profile) : Profile to clear, modified in place.
Returns: Nothing. The profile is mutated.
RowStats
Aggregated statistics for every row of a single bar's footprint.
Fields:
n (series int) : Number of rows. Zero when the footprint holds no data.
total (series float) : Sum of row volume across the bar.
avg (series float) : Mean volume per row.
maxVol (series float) : Volume of the heaviest row, i.e. the POC row.
minVol (series float) : Volume of the lightest row.
pocVol (series float) : Same as maxVol, kept for readability at call sites.
pocTop (series float) : Upper price bound of the POC row.
pocBot (series float) : Lower price bound of the POC row.
pocMid (series float) : Midpoint of the POC row.
pocIdx (series int) : Index of the POC row inside the rows array, -1 when empty.
buy (series float) : Aggressive buy volume of the bar, derived as (total + delta) / 2.
sell (series float) : Aggressive sell volume of the bar, derived as (total - delta) / 2.
delta (series float) : Net delta of the bar summed across rows.
buyImb (series int) : Count of rows flagged as buy imbalances.
sellImb (series int) : Count of rows flagged as sell imbalances.
top (series float) : Highest price covered by any row.
bot (series float) : Lowest price covered by any row.
rowH (series float) : Height of one row in price units.
Span
A contiguous group of rows inside one bar, reported as a price span.
Fields:
top (series float) : Upper price bound of the span.
bot (series float) : Lower price bound of the span.
idxA (series int) : Index of the first row of the span.
idxB (series int) : Index of the last row of the span.
count (series int) : Number of rows in the span.
vol (series float) : Total volume inside the span.
delta (series float) : Net delta inside the span.
Slice
Volume measured over an arbitrary price interval, with partial rows counted pro rata.
Fields:
total (series float) : Volume inside the interval.
buy (series float) : Aggressive buy volume inside the interval.
sell (series float) : Aggressive sell volume inside the interval.
delta (series float) : Net delta inside the interval.
share (series float) : Interval volume divided by the bar's total volume, 0 to 1.
Profile
Composite volume profile accumulated from several bars' footprints.
Fields:
step (series float) : Price bucket size. Rows are folded into buckets of this height.
price (array) : Bucket centre prices, kept sorted ascending.
vol (array) : Volume per bucket, index-aligned with `price`.
dlt (array) : Delta per bucket, index-aligned with `price`.
Bibliothèque

XeL OnlineRecursionXeL OnlineRecursion is a Pine Script library for online and streaming statistical estimation on continuous numerical and financial data.
The library is designed around recursive statistical populations whose retained state is updated observation by observation. Most recursive components use constant retained memory and O(1) work per observation, making them suitable for indicators and models that require adaptive statistics without repeatedly recalculating an entire historical window.
OnlineRecursion is statistical infrastructure rather than a trading signal, strategy, or standalone indicator. It is intended to be imported and composed by other Pine scripts.
CORE DESIGN
The library separates four conceptual layers:
Streaming and population mechanics.
Generic retained statistical state.
Derived statistical interpretations.
Finance-oriented evidence and recursive weighting models.
A central design principle is that retained state represents a statistical population. Statistics that can be derived from an existing population are computed from that state rather than introducing unnecessary independent recursions.
STATISTICAL TOOLS
The library includes:
First-order recursive filtering and recursive extrema estimation.
Sample-and-hold, settlement, accumulation, and exact rolling-sum tools.
Fixed-memory P2 cumulative quantile estimation.
Adaptive quantile and expectile estimation.
Adaptive conditional tail-mean estimation.
Adaptive Huber location estimation.
Adaptive MAD and Gaussian-equivalent robust scale.
Recursive univariate moments through fourth order.
Variance, sigma, skewness, kurtosis, and effective sample size.
Recursive covariance and correlation.
Recursive linear-regression views including beta, intercept, and R-squared.
Recursive Heavy-Tail distribution estimation.
Relative-return, relative-projection, and additive-moment transforms.
Recursive decay, anchored, participation, and composite-alpha constructors.
Market-participation models.
Market-dispersion models.
POPULATION SEMANTICS
OnlineRecursion treats population geometry as part of the mathematical definition of an estimator.
Depending on the component, the represented population may be:
Cumulative.
Finite rolling.
Exponentially weighted.
Anchored.
Conditional.
Observation-clock.
Event-clock.
These population interpretations are not assumed to be interchangeable.
Initialization, missing observations, reset behavior, recursive coefficients, and population boundaries are therefore explicit estimator semantics rather than incidental implementation details.
Where defined as a recursive feedback coefficient, alpha generally follows a convention. Exact initialization behavior is defined by each estimator because creation of a new statistical population is not always equivalent to an ordinary recursive update.
FINANCE-ORIENTED EVIDENCE
The library includes reusable tools for constructing adaptive market evidence, including time-decay weighting, participation-based weighting, relative-return transformations, and recursive market-dispersion models.
Available dispersion interpretations include:
Mean displacement.
Realized movement.
Drawdown.
Upthrust.
Directional stress peaks.
Average directional stress.
Participation models allow recursive weighting to respond to different market-population relationships rather than treating every observation as equally informative.
The chart accompanying this publication demonstrates library mechanics on NQ continuous futures using hourly observations and Open Interest participation.
The upper and lower dispersion plots, recursive mean, and lower-pane statistic illustrate one possible composition of exported library functionality.
These plotted outputs are demonstrations of statistical mechanics. They are not trading signals or recommended parameter settings.
HEAVY-TAIL MODEL
The Heavy-Tail estimator combines generic recursive moment state with additional model-specific interpretations such as Student-t degrees of freedom, t-distribution scale, and absolute-innovation scale.
HeavyTail is one statistical interpretation built on the generic moment backbone. The library does not assume that this model is appropriate for every market, instrument, or application.
USAGE
Import the library from another Pine Script and use the exported state types, methods, enumerations, or functional interfaces required by the application.
Stateful interfaces provide explicit control over retained state and update timing. Functional interfaces are also provided where convenient for series-oriented use.
Some estimator compositions intentionally require caller-controlled timing.
For example, when one adaptive estimator supplies a threshold, center, or scale to another estimator, the caller may need to use the previously retained value to avoid unintended same-observation feedback.
MISSING DATA AND CALLER POLICY
Market-data-dependent functions can return na when required information is unavailable or when the requested statistical relationship is not currently defined.
Fallback behavior intentionally remains with the importing application when the library cannot define the relationship mathematically.
This prevents unavailable data from being silently converted into a different statistical assumption.
LIMITATIONS
OnlineRecursion does not provide:
Entry or exit logic.
Trading recommendations.
Profitability claims.
A guarantee that any estimator is appropriate for a particular market.
Recursive estimators depend on their coefficient policy, population definition, and initialization semantics.
A recursive population is not automatically equivalent to a finite rolling-window population merely because their outputs may appear similar.
Users should therefore select estimators and coefficient models according to their statistical meaning rather than treating all recursive parameters as interchangeable smoothing controls.
DESIGN INTENT
OnlineRecursion is intended to provide reusable statistical infrastructure from which higher-level models can be composed.
The architecture follows this separation:
Foundational state represents the retained population.
Derived statistics interpret that population.
Models add model-specific assumptions.
Applications decide how statistical evidence is used.
This separation is intended to keep generic statistical machinery independent from application-specific trading logic.
VERSION
This first TradingView library publication corresponds to XeL OnlineRecursion development release 1.0.0-rc.2 , dated 2026-09-04.
TradingView library publication revisions such as /1 are independent of the project's development release numbering. Bibliothèque

Bibliothèque

Bibliothèque

Pine Script Utility Library [1CG]Pine Script Utilities
Building a Pine script often means writing the same supporting code again: setting up timezone choices, converting prices to ticks or pips, updating chart drawings, or working out which candles belong to a trading session.
Pine Script Utilities brings these everyday tasks into one reusable toolbox. Its purpose is to help script authors spend more time on what makes their indicator useful and less time rebuilding common tools.
This is a library for Pine Script v6. You use it inside your own indicator or strategy; adding the library alone does not produce a chart display. You can use a single helper or combine several parts of the library as your script grows.
Consistent choices for your settings
Give users familiar choices without recreating the same lists in every script. The library supplies reusable options for:
Timezones, including the symbol's exchange timezone.
Hours, minutes, quarter-hour times and common durations.
Line styles, thickness, extension direction and label styles.
Text size and horizontal or vertical alignment.
Session presets and the starting points for session high and low lines.
It also turns these selections into the values Pine needs to use them. Your script still decides which settings to offer and how to arrange them.
Time and timezone tools
Work with clock times, session schedules and chart timing without repeatedly writing the conversion code yourself. Helpers let you build and read time values, convert between clock times and minutes, calculate durations, check session membership and limit processing to a chosen history window.
For example, you can define a session in New York time even when the symbol uses a different exchange timezone. Named timezones allow session boundaries to follow local daylight-saving changes. Overnight schedules are supported, so a session can start in the afternoon and finish the following morning.
Everyday price and quantity conversions
Use the same conversion tools across different scripts:
Convert a price movement into ticks or pips, or convert those distances back into price.
Override the pip size when a broker's price feed needs a different convention.
Read the symbol's price precision, tick value and asset category.
Round quantities down to a chosen increment.
Calculate a position's notional value from quantity, price and the symbol's point value.
For example, a candle-range display could show its size in ticks instead of a raw price difference. These are general conversions; account-risk sizing and risk/reward calculations belong in a separate risk library.
Easier drawing maintenance
Once your script has created a drawing, the library can help keep it up to date. Change the position, appearance or text of lines, labels and boxes, and update existing table cells. Supply the properties you want to change and leave the others as they are.
Cleanup helpers remove groups of lines, labels, boxes or connected-line drawings called polylines. You can also keep a line collection within a chosen size and turn lists of times and prices into points for chart drawings. This gives scripts a common way to manage their chart objects as new data arrives.
Session tracking beyond simple clock checks
For scripts that need session ranges, the library can track the opening price, high, low and latest closing price, along with the times of the highs and lows. Use a preset schedule or define your own, track multiple sessions separately, and retrieve the current session or earlier completed sessions.
It also handles several details that can otherwise produce confusing chart results:
A session can start or finish partway through a candle. Where needed, available one-minute data helps exclude prices from outside the session. For example, a 09:10 start on a 15-minute chart should not include the earlier prices from the 09:00 candle.
Session prices and displayed line lengths stay separate. You can collect prices until noon and keep the resulting levels visible later without changing the session's high or low.
High and low lines can start from the session opening, the session end, or the time each extreme occurred.
When trading reopens after a long closure, eligible line endpoints can carry forward across the missed days. An overnight session interrupted by the closure can resume as the same session, preserving its earlier prices.
Stored sessions can be kept by record count, so a script can retain actual observations instead of treating empty weekend dates as trading sessions.
The session tools use ordinary chart candles where those candles are sufficient. They can request one-minute data for candles that contain a session boundary, and several sessions can share that data.
Building blocks for your own indicators
You could use these tools for a session-range overlay, a candle-size display, a dashboard with consistent text and styles, or an indicator that marks a chosen time window. Time-window helpers provide the opening and closing times and help your script decide when to draw the window.
The companion session example demonstrates how these pieces fit together. It keeps a chosen number of session records, draws the retained history, and updates the current session as prices arrive. Its complete appearance and additional features are choices made in the example; you can build a different display using the same utilities.
Getting started
Import the library into a Pine v6 script and start with the helpers you need. Simple conversions and drawing helpers can be used independently. Session tracking needs a little more setup because your script keeps the session records and decides how to display them. The full guide explains that workflow, while the API reference lists the available functions and their arguments.
A few things to know
Session tracking is intended for standard intraday time-based charts. Its one-minute boundary checks apply to chart timeframes above one minute.
Custom session tracking uses one start and end time, such as 1600-0400. Presets describe regular clock schedules, not complete holiday or lunch-break calendars.
Weekend and closure adjustments happen when reopening data arrives. The library does not predict future market closures.
Accurate ranges depend on available price history. If required one-minute data is missing, the library does not replace it with a whole candle that could contain out-of-session prices; the resulting range may be incomplete.
Pip sizes, quantity increments and contract values can differ between feeds and instruments. Use the appropriate values for your symbol.
Your script controls its drawings, alerts and history limits. TradingView's data and drawing limits still apply.
Bibliothèque

TradeManagementTradeManagement is a Pine Script® library designed to simplify common trade-management and position-sizing calculations in TradingView strategies.
The library provides reusable functions for calculating:
Take-profit prices
Stop-loss prices
Risk/reward-based take-profit prices
Position size based on monetary risk
Position size based on risk per unit/contract
Current strategy entry price
Features
tpPrice()
Calculates a take-profit price using a percentage.
You can specify whether the trade is long or short.
slPrice()
Calculates a stop-loss price using a percentage.
You can specify whether the trade is long or short.
tpRiskReward()
Calculates a take-profit price based on the distance between the entry price and stop-loss price, using a selected risk/reward multiplier.
For example, you can use a 2 multiplier for a 1:2 risk/reward target.
positionSize()
Calculates the position quantity based on:
Entry price
Stop-loss price
Maximum monetary risk
The calculation uses TradingView's symbol-specific syminfo.pointvalue.
positionSizeByRiskQuantity()
Calculates the position quantity based on:
Entry price
Stop-loss price
Risk amount per unit/contract
Use this when you want to specify risk per contract (e.g., "Risk 0.01 per contract") rather than total monetary risk.
entryPrice()
Returns the current strategy's average entry price when a position is open.
This allows you to keep your strategy code clean while using the same trade-management functions across multiple strategies.
Important Note About Position Risk
The positionSize() function calculates the position quantity based on the specified monetary risk. However, the final risk may not always exactly match the risk amount entered.
This is because some markets or trading environments only allow specific quantity increments, such as whole-number quantities:
1, 2, 3, ...
For example, you may enter $5 as your maximum intended risk, but the calculated position size could result in an actual risk of $3.79.
This happens because the required position size might be something like 1.3, but the market or broker may only allow a quantity such as 1 or 2.
Therefore, the risk input should be considered the maximum intended risk, while the actual risk depends on the quantity precision or increment supported by the specific symbol and trading environment.
Strategy Compatibility
This library is intended primarily for use with TradingView strategies.
The position-sizing and entry-price functions rely on TradingView strategy information and symbol-specific properties.
Risk Disclaimer
This library provides calculation tools and does not guarantee a specific trading result or risk outcome.
Always verify the calculated position size, stop-loss distance, quantity rules, and actual monetary risk for the specific market, broker, or exchange before using the calculations in live trading.
Bibliothèque

kNNLorentzianMachineLearningA high-performance, quant-grade machine learning library written in Pine Script v6, implementing a k-Nearest Neighbors (kNN) classification engine optimized for algorithmic trading. This library features a zero-data-leakage architecture, dynamic memory pre-allocation, and a specialized distance metric designed to evaluate historical market state similarities efficiently.
🔷 Introduction
For quantitative and algorithmic traders using TradingView and Pine Script v6, this library provides an institutional-grade machine learning architecture that moves far beyond basic, traditional technical indicators.
When it comes to feature scalability, the engine is designed to handle a dynamic and unrestricted number of features. You simply pass an array of your chosen technical features, and the library automatically adapts its internal matrix structure to accommodate them. The matrix allocates columns for your features while reserving the final column specifically for the historical target direction. For optimal performance and to avoid the curse of dimensionality—where distance metrics lose precision in overly complex spaces—it is best to use a compact, orthogonal set of three to eight features, such as balanced combinations of momentum, volatility, and volume indicators.
A critical advantage for backtesting integrity is the zero-data-leakage design. In quantitative finance, accidentally including contemporaneous or future information in historical calculations invalidates your results. This library forces the historical scanning loop to start at index one instead of zero, completely excluding the active current bar from the distance calculation pool. This eliminates lookahead bias entirely and ensures your backtest results reflect true historical precedents.
To handle market noise, the library uses a Lorentzian distance metric with a logarithmic transformation. Standard Euclidean distance metrics often break down during flash crashes or extreme macroeconomic volatility spikes because outliers heavily distort the results. The logarithmic transformation dampens the impact of extreme values, stabilizing the kNN classification engine during turbulent market regimes.
From a performance and runtime perspective, the library implements advanced memory management. By using pre-allocated temporary matrices, it avoids the heavy heap thrashing caused by constant dynamic resizing. Furthermore, the step-size parameter allows the engine to sample historical bars by skipping intervals, meaning you can run deep historical lookbacks across thousands of bars without hitting Pine Script execution timeouts.
Finally, the engine delivers probabilistic confidence scoring rather than rigid binary signals. It evaluates the top-k nearest neighbors and computes a directional confidence ratio. Signals are only triggered when this confidence score breaches your configured threshold, giving algorithmic traders a reliable filter for risk management. Combined with recursive safety checks that catch missing values before they can crash your script, this library offers a robust foundation for live quantitative execution.
🔷 Key Technical Features
🔹 Robust Min-Max Feature Normalization
Dynamic Bounding: Computes local maximums and minimums over a configurable lookback window to normalize raw source values.
Edge-Case Safety: Implements strict safeguards against division by zero and na propagation, defaulting to a median scale baseline when ranges collapse or data is unavailable.
🔹 Historical Matrix State Management
Integrity Validation: Performs deep array inspection to ensure all feature vectors are free of na values before ingestion.
Bounded Rolling Buffer: Automatically maintains a sliding window of historical states, capping memory growth by removing oldest records once the threshold is exceeded.
🔹 Optimized kNN Classification Engine
Zero Data Leakage: Explicitly offsets historical iteration starting points (beginning at index 1) to prevent current-bar lookahead bias.
Memory Optimization & Pre-allocation: Reduces runtime overhead through dynamic step-size sampling and pre-allocated temporary matrix architecture.
Lorentzian Distance Adaptation: Utilizes a logarithmic transformation metric to compute feature distance matrices, mitigating the distorting effects of market outliers.
Confidence Scoring: Aggregates directional outcomes from the top-k nearest neighbors to output a bounded probability metric and a threshold-filtered trading score .
🔷 Function Signatures & API Reference
🔹 f_minmax(src, len)
Normalizes a data series between 0 and 100 using a rolling lookback window.
Return Type: float
🔹 f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Appends validated feature vectors and target directions to the historical memory matrix.
Return Type: void
🔹 f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Executes the kNN distance scan, sorting, and institutional confidence calculation.
Return Type:
Below find a script example to quickly test the library.
//@version=6
indicator("kNN Lorentzian Library API Example ", overlay = true)
import thequantscience/kNNLorentzianMachineLearning/5 as knnLib
// INPUTS & CONFIGURATION
k_neighbors = input.int(8, "k Neighbors", minval=1)
threshold = input.float(0.6, "Confidence Threshold", minval=0.5, maxval=1.0, step=0.05)
max_lookback = input.int(500, "Max Lookback Window", minval=100)
step_size = input.int(1, "Scan Step Size", minval=1)
norm_len = input.int(14, "Normalization Lookback", minval=5)
// FEATURE ENGINEERING & NORMALIZATION
// Extract raw technical indicators and normalize them using the library's f_minmax function
float f1 = knnLib.f_minmax(ta.rsi(close, 14), norm_len)
float f2 = knnLib.f_minmax(ta.cci(close, 14), norm_len)
float f3 = knnLib.f_minmax(ta.mom(close, 10), norm_len)
// Package features into an array
array current_features = array.new_float(0)
array.push(current_features, f1)
array.push(current_features, f2)
array.push(current_features, f3)
// Define the target direction (e.g., did price go up relative to the previous bar?)
float target_direction = close > close ? 1.0 : 0.0
// MATRIX MANAGEMENT & kNN EXECUTION
// Initialize the historical matrix (persisted across bars using 'var')
// Note: matrix columns = number of features + 1 (for the target direction)
var matrix hist_matrix = matrix.new(0, array.size(current_features) + 1, na)
// 1. Update history matrix with current bar's features and target
knnLib.f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
// 2. Execute the kNN classification engine
= knnLib.f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
// PLOTTING & VISUAL FEEDBACK
// Plot buy/sell signals on the chart
plotshape(raw_signal == 1, title="Long Signal", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(raw_signal == -1, title="Short Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
-----------------------------------------------------------------------------
f_minmax(src, len)
Parameters:
src (float) : (float) The raw data series to normalize (e.g., RSI, CCI, Momentum).
len (int) : (int) Lookback period for determining the rolling minimum and maximum.
Returns: (float) The normalized value scaled from 0 to 100, or a default midpoint (50.0) on structural failure.
-----------------------------------------------------------------------------
f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Parameters:
hist_matrix (matrix) : (matrix) The reference matrix storing historical feature rows and targets.
current_features (array) : (array) The current bar's feature vector array to evaluate and ingest.
target_direction (float) : (float) The label/target outcome for the current state (e.g., 1.0 for up, 0.0 for down).
max_lookback (int) : (int) Maximum allowed row capacity for the history buffer to control memory footprint.
Returns: (void) Mutates the history matrix in place.
-----------------------------------------------------------------------------
f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Parameters:
k_neighbors (int) : (int) Number of nearest neighbors to query for classification.
threshold (float) : (float) Confidence probability boundary required to trigger a directional signal (e.g., 0.6).
current_features (array) : (array) The live feature vector evaluated against historical instances.
hist_matrix (matrix) : (matrix) The historical memory matrix containing past states and targets.
step_size (int) : (int) Sampling step size interval to optimize heavy runtime loops.
Returns: (tuple) Returns where signal is 1, -1, or 0, and confidence is a float ratio.
----------------------------------------------------------------------------- Bibliothèque

Pattern Atlas : Geometric [AxeAlgo]Pattern Atlas : Geometric Patterns
WHAT THIS LIBRARY IS
This is a Pine Script v6 library of 17 classical chart pattern detectors — Head and Shoulders, Double/Triple Tops and Bottoms, triangles, wedges, flags, and the rest of the standard technical-analysis catalog built from swing highs and lows rather than single-candle shape. Unlike candlestick patterns, which read one to a handful of fixed bars, chart patterns span a variable, often large number of bars, so this library carries one small piece of state — a rolling history of confirmed swing pivots — that every pattern function reads from. Beyond that, the same philosophy as Library #1 applies: no plotting, no alerts, and no inputs in this script by design, since a library's job is to hand other scripts a clean, reusable, well-documented API, not to draw on a chart itself (Pine doesn't allow a library to plot anything anyway). If you're looking for a ready-to-use indicator built on top of this library, see the companion "Pattern Atlas : Geometric Indicator " script, which imports every function here and turns it into on-chart signals, measured-move price targets, a live scanner table, and alerts.
Chart pattern analysis is one of the foundational tools of classical technical analysis, going back to Edwards and Magee's original work and refined since by researchers like Thomas Bulkowski, whose statistical studies of pattern behavior are the closest thing this field has to an industry-standard reference. The patterns in this library follow that standard catalog, so anyone who already knows what a Head and Shoulders top or an Ascending Triangle looks like will recognize exactly what each function is checking for.
WHY A LIBRARY INSTEAD OF ONE MONOLITHIC INDICATOR
Splitting detection logic out as an importable library means:
- Any Pine coder building their own strategy, indicator, or screener can pull in exactly the pattern checks they need without copy-pasting swing-pivot and trendline math into every new script.
- The detection logic is tested and maintained in one place. When a threshold gets refined, everything importing this library benefits from the update by bumping one version number.
- It keeps the math separate from presentation — how a pattern gets drawn, colored, or alerted on is a completely separate decision from whether the pattern is actually present, and different users want different presentations.
HOW TO IMPORT AND USE IT
Add this line near the top of your script (adjust the version number to whatever the current published version is):
import AxeAlgo/Pattern_Atlas_Geometric/1 as geo
Unlike Library #1, most of the functions here need a shared pivot history to work from. Call trackPivots() exactly once per bar, then pass its result into every detect*() function that needs it:
pivots = geo.trackPivots()
match = geo.detectDoubleTopBottom(pivots)
if match.found
label.new(bar_index, high, match.patternName)
Four functions — detectSpike(), detectFlag(), detectPennant(), and detectIslandReversal() — read directly off recent price action instead of the shared pivot history, so they're called without a pivots argument: geo.detectSpike().
trackPivots() takes three optional parameters: leftBars and rightBars (how many less-extreme bars must surround a candidate swing point before it confirms as a pivot — higher values mean fewer, more significant pivots, at the cost of a longer confirmation lag), and maxPivots (how much pivot history to retain). All three have sensible defaults.
Every detect*() function returns the same structure, called ChartPatternMatch, so the calling pattern is identical no matter which of the 17 you use. It has nine fields:
- found — true if the pattern matched at the evaluated bar, false otherwise.
- patternName — the specific name of what matched (e.g. "Ascending Triangle"), na when not found.
- direction — "bullish" or "bearish".
- pivotBars — bar_index of each pivot the match was built from, in chronological order.
- pivotPrices — price of each pivot, in the same order as pivotBars.
- breakoutLevel — the support, resistance, or neckline level price broke through to confirm the pattern.
- necklineSlope — slope (price per bar) of the breakout line, na when the pattern's breakout level isn't a sloped line.
- barIndex — the bar_index the pattern completes (breaks out) on.
- description — a full sentence naming the pattern and the actual measured price levels that triggered it — genuinely useful for a tooltip or an alert message, not just a repeat of the pattern name.
Two additional exported functions turn that raw match into something more actionable, and both work on any ChartPatternMatch regardless of which detect*() function produced it:
- patternStrength(match) — a 0-100 score for how decisively the confirmation close broke through breakoutLevel, relative to the pattern's own price range. A breakout that clears the level by a meaningful fraction of the pattern's own size scores higher than a one-tick poke through it.
- patternTarget(match) — a classical measured-move price target, projecting the pattern's own height from the breakout point. Returns na for patterns without a reliable height to project from (V-Top/V-Bottom Spike, Island Reversal, Bump-and-Run Reversal).
Every detect*() function also exposes its own set of tunable threshold parameters — how flat a "flat top" has to be, how much two shoulders can differ and still count as equal, and so on — all with sensible defaults so you don't have to touch them unless you want to tighten or loosen a specific pattern's sensitivity for a particular instrument or timeframe.
THE 17 PATTERNS
Reversal patterns (7) — signal a potential change in the prevailing trend:
- Head and Shoulders / Inverse Head and Shoulders — detectHeadAndShoulders(). Three swing extremes with the middle one more extreme than the two roughly-equal outer ones, confirmed when price breaks the neckline connecting the two points between them.
- Double Top / Double Bottom — detectDoubleTopBottom(). Two roughly equal peaks (or troughs) with a retracement between them, confirmed when price breaks back through that retracement level.
- Triple Top / Triple Bottom — detectTripleTopBottom(). The same idea as a Double Top/Bottom with a third roughly-equal touch, confirmed on the break of the support or resistance formed between the touches.
- Rounding Top / Rounding Bottom — detectRoundingTopBottom(). A gradual, curved advance-and-rollover (or decline-and-recovery) between two similar edge levels. Approximate: read from three swing pivots rather than fitting a true curve.
- Diamond Top / Diamond Bottom — detectDiamondTopBottom(). Swing range that widens and then narrows again, confirmed on a break of the resulting support or resistance. Rare and approximate: read from three pivot pairs rather than a clean diamond outline.
- Broadening Formation — detectBroadeningTopBottom(). Diverging highs and lows forming an increasingly volatile range, confirmed on a break of either edge. Approximate: read from two pivot pairs rather than a hand-fitted diverging channel.
- V-Top / V-Bottom (Spike) — detectSpike(). A single sharp extreme with no rounding — a large move into the pivot and an equally large move away from it, both measured against the recent average bar range, within a handful of bars. Self-contained, no pivots argument needed.
Continuation patterns (8) — typically resolve in the direction of the move that preceded them:
- Ascending Triangle — detectTriangleAscending(). Flat resistance with rising support, confirmed on a break above resistance.
- Descending Triangle — detectTriangleDescending(). Flat support with falling resistance, confirmed on a break below support.
- Symmetrical Triangle — detectTriangleSymmetrical(). Converging highs and rising lows, confirmed (bullish or bearish) whichever side the price actually breaks.
- Rising Wedge / Falling Wedge — detectWedge(). Both trendlines slope the same direction and converge; breaks the opposite way from the slope, since the shared-direction move was already losing momentum.
- Bull Flag / Bear Flag — detectFlag(). A strong directional move (the pole), followed by a tight, roughly parallel pullback, confirmed on a break back out in the pole's direction. Self-contained, no pivots argument needed.
- Bull Pennant / Bear Pennant — detectPennant(). The same pole-and-consolidation structure as a Flag, but the consolidation narrows and converges rather than staying parallel. Self-contained, no pivots argument needed.
- Rectangle — detectRectangle(). Price boxed between flat support and flat resistance, confirmed on a break of either edge.
- Cup and Handle / Inverted Cup and Handle — detectCupAndHandle(). A rounded recovery (or decline) back to its starting rim, then a shallow pullback (the handle), confirmed on a break through the rim.
Structural / gap-based patterns (2):
- Bullish / Bearish Island Reversal — detectIslandReversal(). A bar (or small cluster) isolated by a gap on both sides, then abandoned by a gap the other way — an abrupt reversal. Self-contained, pure gap logic, no pivots argument needed.
- Bump-and-Run Reversal — detectBumpAndRun(). A lead-in trendline, then a "bump" phase accelerating well beyond it, then a "run" breaking back through the lead-in line. Approximate: the lead-in line is read from just two pivots rather than a hand-drawn trendline.
WHAT THIS LIBRARY DELIBERATELY DOES NOT DO
No plotting, no drawing, no alertcondition() calls, and no inputs — Pine doesn't allow any of those inside a library in the first place, since a library can never be added to a chart on its own. If you want signals, price targets, a scanner table, or alerts, import this library into your own script (or use the companion "Pattern Atlas : Chart Pattern Scanner " indicator, which does exactly that) rather than expecting this script to render anything by itself.
This library also does not evaluate multi-timeframe data, volume, or broader market structure — it's swing-pivot and trendline geometry only, on purpose, so its behavior is easy to reason about and easy to reuse as one building block among several.
Four of the seventeen patterns are explicitly noted above as approximate: Rounding Top/Bottom, Diamond Top/Bottom, Broadening Formation, and Bump-and-Run Reversal are read from a small, fixed number of swing pivots rather than fitting a true curve or hand-drawn trendline to the data. They will not catch every textbook-perfect example of these shapes, and they may occasionally flag a looser approximation of one. Treat them as a starting point for further chart review, not a final word.
PART OF A LARGER SERIES
This is Library #2 in the AxeAlgo Pattern Atlas — a planned set of Pine libraries splitting pattern detection by the method actually used to find each kind of pattern: candlestick shape (Library #1, already published), classical chart/geometric patterns (this library), harmonic patterns (Fibonacci-ratio XABCD structures), and market-structure concepts (order blocks, liquidity, Wyckoff-style events). Each library is independent and useful on its own; together they're meant to cover technical pattern analysis without forcing unrelated detection methods into the same function.
A NOTE ON REPAINTING
trackPivots() only confirms a swing pivot once rightBars bars have passed since it happened — the same confirmation lag ta.pivothigh()/ta.pivotlow() use, just written out as plain comparisons so it works safely inside a library's exported functions. That means a pivot never moves or disappears once confirmed; it just takes rightBars bars to become known, which is a normal and unavoidable part of swing-pivot detection, not a defect in this library. On the currently-forming bar, a pattern's found status can still change tick to tick as that bar's own high, low, and close move — that's inherent to reading live price action. If you're building persisted signals, drawings, alerts, or price targets on top of these functions (rather than a live "what's happening right now" readout), gate your usage on barstate.isconfirmed so a signal only fires once the bar it describes has actually closed, exactly like the companion scanner indicator does.
DISCLAIMER
This library is a technical analysis tool for identifying classical chart pattern shapes in historical and live price data. It does not predict future price movement, and a detected pattern — including any projected price target — is a description of past price action, not a signal guaranteed to repeat. Nothing in this script constitutes financial advice. Always combine pattern recognition with your own risk management and broader analysis before making any trading decision.
Bibliothèque

Bibliothèque

CapitalCompassCoreCapital Compass Core
Capital Compass Core is the shared Pine Script framework for the Capital Compass ecosystem. It centralizes reusable calculations, state definitions, visual standards, market-context logic, risk logic, portfolio helpers, strategy utilities, panel functions, formatting tools, and alert infrastructure used across Capital Compass scripts.
The library is designed to keep Market Navigator, Tactical Navigator, Strategy Lab, Portfolio Compass, and future Capital Compass tools operating from the same definitions instead of maintaining duplicate implementations across multiple scripts.
Purpose
Capital Compass Core is infrastructure rather than a standalone trading indicator.
The library calculates and standardizes reusable logic. Consuming indicators and strategies remain responsible for user inputs, plots, fills, chart markers, alert conditions, strategy orders, and script-specific interpretation.
Core calculates and standardizes. The consuming script orchestrates and renders.
Core systems
Reusable functionality includes:
• EMA, SMA, RMA, WMA, VWMA, HMA, DEMA, TEMA, and VWAP
• Moving-average structure, compression, expansion, zones, crosses, and standardized MA hierarchy
• 20-SMA / 21-EMA Fast Trend Zone
• Ichimoku calculations
• Bollinger Bands
• ATR, relative volume, drawdown, price-shock, and volatility calculations
• SuperTrend and multi-SuperTrend agreement
• RSI/MFI/MACD momentum components and consolidated momentum states
• Market regime, risk, opportunity, and market-permission scoring
• Tactical market phases and transition states
• Market Navigator state aggregation
• Price structure, pivots, and regular divergence
• Asset-profile presets
• Portfolio allocation and deployment calculations
• Account-context helpers
• Position sizing, ATR stops, targets, trailing logic, reward/risk, R multiples, expectancy, and strategy-quality helpers
• Confirmed higher-timeframe data helpers
• Relative-strength calculations
• Alert-event routing and transition helpers
• JSON and text formatting
• Theme-aware panels, table cells, text, borders, fills, and semantic state backgrounds
State and color standard
Capital Compass uses a consistent semantic visual language:
• Green = bullish / favorable
• Red = bearish / unfavorable
• Orange = caution / transition / sideways / neutral / mixed
• Gray = inactive / unavailable / insufficient data
• Blue = informational / fast-trend reference
• Magenta = major structural reference
Moving-average identity colors are separate from directional state colors. This allows a moving average to retain a recognizable identity while optional Trend mode communicates bullish, bearish, or transitional conditions.
The standardized moving-average hierarchy includes:
8, 13, 20, 21, 34, 50, 55, 89, 100, and 200 periods.
Primary structural references:
• 20 / 21 = fast trend
• 50 / 55 = intermediate trend / caution zone
• 200 = major long-term structural reference
Capital Compass Core also provides theme-aware helpers derived from the active TradingView chart colors so consuming scripts can remain readable across light and dark chart themes.
Capital Compass ecosystem
Market Navigator
Long-term market condition, regime, risk, opportunity, portfolio context, and review.
Tactical Navigator
Tactical trend, momentum, transition, Fast Trend Zone, volatility, and market-phase analysis.
Strategy Lab
Research, hypothesis testing, backtesting support, position sizing, risk planning, and strategy evaluation.
Portfolio Compass
Portfolio allocation, deployment, account context, and long-term capital-management support.
Shared calculations should be imported from Capital Compass Core rather than independently duplicated inside each script.
Library usage
Import the library with:
import DrGetDown/CapitalCompassCore/1 as CC
Examples of shared functionality include:
CC.ma(...)
CC.maColor(...)
CC.fastTrendZone(...)
CC.marketNavigatorState(...)
CC.tacticalPhase(...)
CC.momentumScore(...)
CC.stateColor(...)
CC.panelPos(...)
CC.strategyPlan(...)
Published library versions are intentionally explicit. Consuming scripts should migrate only after a newer Core release has been compiled, tested, and validated.
Design principles
• Maintain one definition for shared calculations and state meanings.
• Separate market-state colors from moving-average identity colors.
• Keep reusable calculations in Core whenever technically practical.
• Keep script-specific interpretation and rendering in the consuming script.
• Avoid unnecessary duplicate or correlated calculations.
• Use confirmed higher-timeframe data where explicitly specified.
• Keep risk and position-sizing mathematics separate from actual strategy order placement.
• Preserve consistent panel placement, formatting, abbreviations, state meanings, and visual behavior across the ecosystem.
• Test significant shared changes before promoting them across dependent Capital Compass scripts.
Limitations
Capital Compass Core does not predict future prices and does not guarantee profitable trades or prevent losses.
Market regimes, momentum states, tactical phases, opportunity scores, risk scores, divergences, moving-average structures, and strategy statistics are analytical classifications based on supplied market data and configured assumptions. They should not be interpreted as guarantees of future performance.
Backtest statistics describe historical results and do not guarantee similar future results.
Portfolio, allocation, deployment, and position-sizing helpers provide mathematical and analytical context only. Actual decisions remain dependent on objectives, portfolio circumstances, risk tolerance, time horizon, liquidity needs, taxes, diversification, and independent research.
Version
Internal Core version: 1.0.0
TradingView library release: /1
Capital Compass
OBSERVE • DISCERN • PREPARE • ACT WISELY
Tuned to the signal. Anchored to the mission. Bibliothèque
