Vantage_UtilsVantage_Utils — Non-trading utilities for Pine Script strategies. A news-calendar state machine and a per-trade P&L tracker, both built as UDT pseudo-classes you instantiate and drive from your script.
─────────────────────────────────────────
WHAT IT DOES
Two capabilities are packaged as instantiable objects (UDT pseudo-classes) so your script holds the state and calls methods rather than threading raw values and globals: a news-calendar state machine that tells you whether the current bar is blocked or delayed by an economic event, and a P&L tracker that accumulates per-trade, session, and daily totals with on-chart labels.
─────────────────────────────────────────
WHAT IT PROVIDES
A news-calendar state machine that consolidates the Vantage_News_Types vocabulary and the Vantage_News / Vantage_News_Historical calendar data behind a single NewsState object. Your strategy asks whether the current bar is blocked or delayed, or when the next trading window starts, and gets the answer back — no need to join event rows against a severity table yourself. Per-type policy overrides and per-severity defaults are configurable. Allows avoiding trading news volatile moments in back testing and live trading.
A P&L tracker (PnLTracker) that computes realized trade P&L with commission, accumulates session and daily totals, detects day boundaries for automatic reset, and manages the per-trade P&L label lifecycle on the chart.
─────────────────────────────────────────
HOW TO USE
A minimal usage example is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation.
Imports Vantage_News, Vantage_News_Historical, and Vantage_News_Types to expose the consolidated news calendar. Library

Library

Vantage_News_TypesVantage_News_Types — Shared vocabulary of US economic event types and a default severity taxonomy for Pine Script news-filtering strategies.
─────────────────────────────────────────
WHAT IT DOES
Publishes a shared set of named event-type constants and a default severity mapping so that news-calendar data libraries, severity-override tables, and consuming strategies can all agree on what each event type means without maintaining their own copy of the list.
─────────────────────────────────────────
WHAT IT PROVIDES
Named constants for 125+ tracked US economic events — CPI, PPI, PCE, FOMC statements and speakers, non-farm payrolls, ISM, retail sales, GDP, housing, consumer confidence, crude inventories, Treasury auctions, bank holidays, and more. Each is a compact integer ID you can store in a packed news table.
A default severity taxonomy expressed relative to equity-index futures — Severity 1 — Watch (low-impact, not expected to move the market), Severity 2 — Delay entry (pause entries until a configurable window after release), and Severity 3 — Block the session (do not trade on a day carrying this event). Callers for other instruments can still use the type IDs and apply their own mapping.
Time helpers for the HHMM → milliseconds conversion used by packed news tables, and append helpers for building up parallel date / time / type-id arrays.
─────────────────────────────────────────
HOW TO USE
A minimal usage example is in the comment block at the top of the source file. Updated weekly as new event types are observed or severity defaults change. Library

AvwapLibLibrary "AvwapLib"
Shared functions: AVWAP, stage classification, position sizing,
swing detection, and risk helpers. Used by all strategy() scripts.
NOTE: rs_vs_spy() cannot live here (request.security() banned in
library exports) — each strategy implements it inline.
avwap(src, anchor_bar, max_lookback)
Anchored VWAP from a specific bar to current bar.
Uses loop approach with bounded max_lookback for robustness.
Parameters:
src (float) : Source price (typically hlc3)
anchor_bar (int) : Bar index of anchor point (from find_swing_high/low)
max_lookback (simple int) : Maximum bars to look back (cap for performance, default 500 ~2yr daily)
Returns: AVWAP value, or na if anchor invalid or out of range
avwap_slope(avwap_val, lookback)
AVWAP slope — rate of change over lookback period.
Parameters:
avwap_val (float) : AVWAP series
lookback (simple int) : Number of bars for slope calculation
Returns: Slope (positive = rising, negative = falling), or na
dcr()
Daily Closing Range — where price closed within the bar's range.
Returns: DCR as percentage (0 = closed at low, 100 = closed at high)
rvol(period)
Relative Volume — current bar volume vs historical average.
Uses volume offset to avoid including current bar in average.
Parameters:
period (simple int) : Lookback period for average calculation
Returns: RVOL ratio (>1 = above average)
is_stage2()
Stage 2 check (simplified Weinstein model).
Conditions: price > SMA50, SMA50 rising (vs 10 bars ago), price > SMA200.
Returns: true if all Stage 2 conditions met
calc_shares(entry, stop, risk_pct, equity)
Position size: shares = floor(equity * risk% / risk_per_share).
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
risk_pct (float) : Risk as decimal (0.01 = 1%)
equity (float) : Account equity
Returns: Number of shares (integer), 0 if invalid
rr_valid(entry, stop, target, min_rr)
Validate risk/reward ratio meets minimum threshold.
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
target (float) : Target price
min_rr (float) : Minimum required R:R (e.g., 2.0 for 1:2)
Returns: true if R:R >= min_rr
confirmed()
Returns true only on confirmed (closed) bars.
MUST gate every entry/exit signal to prevent repainting.
Returns: true if bar is confirmed
find_swing_high(strength)
Bar index of the most recent confirmed swing high.
Uses ta.pivothigh — confirmed 'strength' bars after the actual high.
Result persists (via var) until a new swing high is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing high, or na if none found yet
find_swing_low(strength)
Bar index of the most recent confirmed swing low.
Uses ta.pivotlow — confirmed 'strength' bars after the actual low.
Result persists (via var) until a new swing low is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing low, or na if none found yet Library

Library

Library

KeyLevelsLibrary "KeyLevels"
Library for common trading levels including VWAP, session levels (Asia, London, NYC, Comex IB), HTF OHLC, and Opening Ranges.
--- IMPLEMENTATION INSTRUCTIONS ---
1. Save this script as a Library named "KeyLevels".
2. In your indicator/strategy, import it: `import /KeyLevels/1 as kl`
3. To get the data object, call: `levels = kl.getLevels()`
4. Access levels using dot notation: `levels.loH` (London High), `levels.nycH` (NYC High), `levels.cibH` (Comex IB High).
5. To get all levels in a single array for loops: `levelArray = kl.toArray(levels)`
--- TIMEZONE NOTE ---
The default timezone is "UTC-5" (New York). For accurate seasonal adjustments, use "America/New_York".
getLevels(vwapAnchor, vwapMult, rollingLen, htfAnchor, tz)
getLevels Calculates and returns a KeyLevelsData object with comprehensive trading levels.
Parameters:
vwapAnchor (string) : Anchor condition for the main VWAP (e.g., "1D", "1W").
vwapMult (float) : Standard deviation multiplier for VWAP bands.
rollingLen (int) : Length for the rolling VWAP calculation.
htfAnchor (string) : Anchor for the HTF VWAP (e.g., "1W", "1M").
tz (string) : Timezone for session calculations (default: "UTC-5").
Returns: A `KeyLevelsData` object containing the levels.
toArray(data)
toArray Converts a KeyLevelsData object into a flat array of floats.
Parameters:
data (KeyLevelsData) : The KeyLevelsData object to convert.
Returns: An array of floats containing all levels.
KeyLevelsData
KeyLevelsData Master structure to hold all calculated key levels (Flattened).
Fields:
vwapCenter (series float)
vwapUpper (series float)
vwapLower (series float)
htfVwapCenter (series float)
htfVwapUpper (series float)
htfVwapLower (series float)
rollingVwap (series float)
dailyOpen (series float)
asO (series float)
asH (series float)
asL (series float)
asC (series float)
loO (series float)
loH (series float)
loL (series float)
loC (series float)
nycO (series float)
nycH (series float)
nycL (series float)
nycC (series float)
cibO (series float)
cibH (series float)
cibL (series float)
cibC (series float)
ibO (series float)
ibH (series float)
ibL (series float)
ibC (series float)
ibMid (series float)
o5O (series float)
o5H (series float)
o5L (series float)
o5C (series float)
o15O (series float)
o15H (series float)
o15L (series float)
o15C (series float)
o30O (series float)
o30H (series float)
o30L (series float)
o30C (series float)
pdO (series float)
pdH (series float)
pdL (series float)
pdC (series float)
pwO (series float)
pwH (series float)
pwL (series float)
pwC (series float)
cwO (series float)
cwH (series float)
cwL (series float)
cwC (series float)
cmO (series float)
cmH (series float)
cmL (series float)
cmC (series float)
settlement (series float) Library

Library

Library

Library

APExitManagerLibrary "APExitManager"
apExitManager(entryID, isLong, rangeSize, rangeHigh, rangeLow, slMethod, tpMethod, slPercent, tpPercent, atrMultSL, atrMultTP, stackedCount, stackedTotalPercent, usePartial, partialPct, atrLength, superLength, superFactor)
Parameters:
entryID (string)
isLong (bool)
rangeSize (float)
rangeHigh (float)
rangeLow (float)
slMethod (string)
tpMethod (string)
slPercent (float)
tpPercent (float)
atrMultSL (float)
atrMultTP (float)
stackedCount (int)
stackedTotalPercent (float)
usePartial (bool)
partialPct (float)
atrLength (simple int)
superLength (simple int)
superFactor (float) Library

Library

DafeRCMLibRolling Confidence Matrix Library (RCM)
A Structural Evidence Accumulation Engine for Pine Script Developers
What This Library Does
The Rolling Confidence Matrix (RCM) is a developer library that provides a stateful structural analysis engine for Pine Script indicators. It maintains rolling evidence buckets that accumulate and decay observations about market structure on every bar, then synthesizes those observations into confidence scores, a directional state classification, and a set of modulation outputs that downstream indicators can consume.
The library is designed to be algorithm-agnostic. It does not generate signals, draw lines, or produce visual output. It computes structural context that other indicators use to make better decisions — whether that indicator is a Supertrend, a moving average crossover, a Bollinger Band system, or a machine learning model.
The Problem This Solves
Traditional indicators are structurally blind. A Supertrend calculates band width from ATR alone. A moving average crossover fires regardless of whether the cross happens during a structural breakout or inside exhaustion chop. A Bollinger Band squeeze looks identical mathematically whether it precedes a genuine expansion or a false breakout.
These indicators lack the ability to evaluate what kind of price action is producing their signals. The RCM addresses this by maintaining a persistent, per-bar structural memory that any indicator can query.
How It Works: The Five Evidence Buckets
The RCM tracks five categories of structural evidence, accumulated separately for bull and bear sides (10 buckets total). Each bucket decays by a configurable rate every bar, accumulates when its specific conditions are detected, and is hard-capped to prevent runaway values.
Impulse — Detects directional thrust bars. Criteria: body exceeds the 10-bar average body by 15%, close position is in the upper 30% (bull) or lower 30% (bear) of the bar's range, and the bar's range exceeds the 10-bar average range by 5%. Volume confirmation adds additional evidence when the volume ratio exceeds 1.2x the 20-bar average.
Structure — Detects swing-level events. Criteria: price closes above the 5-bar highest high (swing break), price sweeps below a swing low and reclaims it on a bullish close (reclaim), or price wicks through a swing level but closes back inside (sweep absorption). Each event type contributes a different evidence weight, reflecting its structural significance.
Exhaustion — Detects reversal pressure. Criteria: a bearish-body bar with a lower wick exceeding 45% of the total range on volume above 1.2x average contributes bull exhaustion evidence (potential buying absorption). The inverse applies for bear exhaustion. This bucket represents counter-trend pressure building within the current move.
Continuation — Detects trend persistence. Criteria: the EMA(21) of HLC3 has a positive slope, price is above the anchor, and the current close exceeds the previous close. This bucket also has asymmetric decay: when price moves to the wrong side of the anchor, continuation evidence decays at 62% per bar instead of the standard rate. Anchor crosses trigger a 50% immediate reduction.
Compression — Detects range contraction. Criteria: the current bar's range is below 80% of the 10-bar average range, and the ATR(14) to SMA(ATR,30) ratio is below 0.95. Compression evidence accumulates on the side of the anchor (bull compression above, bear compression below), representing potential energy buildup before expansion.
Bucket Caps
Each bucket has a defined maximum to prevent any single evidence type from dominating the confidence calculation:
Impulse: 25
Structure: 30
Exhaustion: 20
Continuation: 20
Compression: 15
Confidence Computation
Bull and bear confidence scores are computed as weighted sums of their respective five buckets:
bullConf = bullImpulse × wImpulse + bullStructure × wStructure +
bullExhaustion × wExhaustion + bullContinuation × wContinuation +
bullCompression × wCompression
Default weights are: Impulse 1.20, Structure 1.35, Exhaustion 1.15, Continuation 1.00, Compression 0.90. Structure carries the highest default weight because swing-level events are the most structurally significant observations.
From these scores, the library derives:
Net Confidence: bullConf − bearConf
Activity: bullConf + bearConf (total evidence in the system)
Dominance: netConf / activity (how one-sided the evidence is, range −1 to +1)
Bull/Bear Pressure: each side's share of total activity (range 0 to 1)
The Three-State Engine
The state engine uses hysteresis to prevent flickering between states. Entering a state requires strong evidence; holding a state requires only moderate evidence.
Entry Conditions (Transition → Bull/Bear):
Net confidence exceeds the entry threshold (default: 12.0)
AND dominance exceeds the dominance threshold (default: 0.18)
Hold Conditions (Bull/Bear → Transition):
A state is lost when ANY of:
Net confidence drops below the hold threshold (default: 5.0)
Opposing pressure exceeds the flip pressure threshold (default: 0.58)
Erosion (peak confidence minus current) exceeds 35% of current confidence
This hysteresis design means the engine requires conviction to enter a directional state but gives the trend room to breathe once established.
Substates
When the engine is in Transition (state = 0), it internally classifies the type of transition based on which evidence buckets are dominant:
Early (substate 1): Within 3 bars of losing a directional state. Evidence is collapsing.
Contested (substate 2): Both bull and bear confidence exceed 50% of the entry threshold. Both sides have material evidence.
Rotational (substate 3): Exhaustion buckets represent more than 35% of total non-compression evidence. The market is churning.
Compression (substate 4): Compression buckets exceed 35% of total evidence while impulse is below 15%. Energy is building.
The external state remains 0 for all substates. Consumers who need granularity can query st.substate.
Damage Detection
When the engine is in a directional state, it evaluates structural compromise on every bar by accumulating a damage score from seven independent checks:
For a Bull state, damage accumulates from:
Price below the anchor (+1.5)
Bear impulse condition detected (+1.0)
Upper wick ratio exceeds 35% (+0.75)
Anchor slope is negative (+1.0)
Bear pressure exceeds 45% (+1.0)
Close and high are both lower than previous bar (+0.75)
Price crossed below the anchor this bar (+1.25)
Maximum possible damage score per bar: 7.25. When the score exceeds the damage threshold (default: 4.0), the trend is flagged as damaged.
Damage Response
When damage is detected, the engine modifies the active side's evidence buckets:
Continuation is reduced by (0.25 × damageDecayMult) — default removes ~44%
Impulse is multiplied by damageImpulseCut — default retains 88%
Structure is multiplied by 0.92
Opposing exhaustion receives +1.5
Opposing impulse receives +1.0
This creates a natural degradation cycle: damage weakens the active trend's evidence while strengthening the opposing side's, making a transition more likely without forcing it.
Integrity Score
The library computes a continuous structural integrity measure from 0.0 (broken) to 1.0 (fully intact), derived from four components:
Erosion component (max −0.30): How far current confidence has fallen from its peak
Damage component (max −0.30): Current damage score relative to threshold
Opposing pressure (max −0.20): Counter-trend pressure magnitude
Transition duration (max −0.15): How long the engine has been in transition state
External evidence modifiers can also adjust integrity by ±0.1.
Directional Permissions
Rather than a simple pass/fail gate, the library outputs four permission values:
allowLong (bool) : Structural permission to take long positions
allowShort (bool): Structural permission to take short positions
preferLong (float, 0−1): Strength of structural preference for longs
preferShort (float, 0−1): Strength of structural preference for shorts
In Bull state: longs are allowed, shorts are blocked unless the trend is damaged (allowing counter-trend fades). preferLong equals the confidence strength. In Bear state: the inverse. In Transition: both sides are allowed, preference leans toward whichever side has more evidence.
External Evidence Sockets
The library accepts additive evidence injection from external systems through the ExternalEvidence type. External evidence is applied after internal bucket computation but before state transitions, meaning it can influence confidence but cannot directly set state.
ev = rcm.ExternalEvidence.new(bullEvidence=3.0, source="dreamer")
st := rcm.inject(st, ev)
External evidence is reset to zero after each update() call. This prevents stale external data from persisting.
Modulation Outputs
The library provides purpose-built modulation functions for different indicator types:
Band Modulation (get_band_mod): Returns a float multiplier for band/envelope width. Bands tighten during high-confidence directional states and widen when damage is detected. Used by Supertrend, Bollinger Band, and PSAR-type indicators.
Score Modulation (get_score_mod): Returns an additive modifier for directional scores. When a score's direction aligns with the RCM state, it receives a confidence-proportional boost. When it opposes, it receives a penalty. Used by signal-scoring systems.
Signal Gate (get_gate): Returns a boolean indicating whether signals should be permitted. When transition blocking is enabled, all signals are suppressed during Transition state.
Full Package (get_modulation): Returns all outputs in a single RCMModulation struct including band mod, score mod, gate, permissions, integrity, state color, and regime label.
Configuration
The library ships with three preset configurations:
default_config(): Balanced settings suitable for 15m−1H timeframes
scalp_config(): Faster decay (0.75), lower thresholds, higher impulse weight — optimized for 1m−5m
swing_config(): Slower decay (0.88), higher thresholds, higher structure weight — optimized for 4H−Daily
All 16 configuration parameters can also be set individually through the RCMConfig constructor.
Developer Integration Guide
Step 1: Import and Initialize
import DskyzInvestments/DafeRCMLib/1 as rcm
var rcm.RCMState st = rcm.RCMState.new()
var rcm.RCMConfig cfg = rcm.default_config()
Both objects must be declared with var for state persistence across bars.
Step 2: Update Every Bar
st := rcm.update(st, cfg)
Call update() exactly once per bar. It handles all evidence detection, decay, confidence computation, damage detection, state transitions, substate classification, and integrity scoring.
Step 3: Query Modulation Outputs
For band-based indicators (Supertrend, BB, PSAR):
band := band * rcm.get_band_mod(st, 0.45, 1.10)
For score-based systems (signal scoring, ML models):
fusedScore = rawScore + rcm.get_score_mod(st, rawScore, 0.25)
For signal gating:
buySignal := buySignal and rcm.get_gate(st, true)
For directional permissions:
rcm.RCMPermissions perms = rcm.get_permissions(st)
if perms.allowLong and perms.preferLong > 0.3
// High structural preference for longs
Step 4: Optional — Inject External Evidence
if myDreamerScore > 2.0
ev = rcm.ExternalEvidence.new(bullEvidence=2.0, source="dreamer")
st := rcm.inject(st, ev)
// inject() must be called BEFORE update()
Step 5: Optional — Use Dashboard Helpers
rcm.conf_bar(st.bullConf, 130, 8) // Returns "████░░░░"
rcm.state_text(st) // Returns "▲ BULL"
rcm.damage_text(st) // Returns "Intact"
rcm.integrity_text(st) // Returns "87.3%"
rcm.state_color(st, bullCol, bearCol, transCol)
Step 6: Optional — Narrative Text
= rcm.narrative_regime(st, bullCol, bearCol, transCol, dimCol)
= rcm.narrative_kinetics(st, accentCol, dimCol)
= rcm.narrative_structure(st, bullCol, bearCol, transCol, dimCol)
What This Library Does Not Do
It does not generate buy/sell signals
It does not draw on the chart
It does not use request.security or access external timeframes
It does not use request.footprint (consumers can inject footprint-derived evidence through the external socket)
It does not persist data beyond the current chart's bar history
It does not adapt its own parameters automatically
The library computes structural context. What the consuming indicator does with that context is entirely the developer's decision.
Companion Demo
The DafeRCMLibDEMO indicator demonstrates every function and output of this library
using a simple EMA crossover system as the base indicator. It includes:
Modulated ATR bands showing get_band_mod() in action
Trade signals gated by get_permissions() and get_gate()
State shift and damage markers
Substate classification labels
Evidence bucket subplots for all 10 buckets
Confidence, integrity, and modulation output subplots
Full quantitative dashboard and narrative panel
— Dskyz, Trade with insight. Trade with anticipation. Library

BandsLibLibrary "BandsLib"
f_calc_survival_bands(basis, dev, shift_z, prob_pct, mr_shift)
Parameters:
basis (float) : Base price level (MA, median, etc.)
dev (float) : Standard deviation or volatility measure
shift_z (float) : Directional shift factor (e.g., vector pressure, momentum)
prob_pct (float) : Survival probability percentage (e.g., 10 = 10%)
mr_shift (float) : Mean reversion shift (optional, contrarian to shift_z)
Returns: Tuple of upper and lower survival bands
f_detect_squeeze(band_up, band_dn, price, damping)
Parameters:
band_up (float) : Upper band level
band_dn (float) : Lower band level
price (float) : Current price
damping (float) : Correlation damping factor (0-1)
Returns: Tuple of bullish/bearish squeeze signals and bandwidth percentile
f_detect_confluence(basis, fv, dev, tol_mult, min_lines)
Parameters:
basis (float) : Base price level (MA, median, etc.)
fv (float) : Fair value or equilibrium price
dev (float) : Standard deviation or volatility measure
tol_mult (float) : ATR multiplier for clustering tolerance
min_lines (int) : Minimum number of converging lines to trigger confluence Library

BasketLibLibrary "BasketLib"
f_calc_correlation_score(base_return, candidate_return, corr_len, smooth_len, is_self)
Parameters:
base_return (float) : Base asset 1-bar return
candidate_return (float) : Candidate asset 1-bar return
corr_len (int) : Correlation calculation length
smooth_len (simple int) : EMA smoothing length
is_self (bool) : Whether candidate is the base asset itself
Returns: Correlation score (0.7 * raw + 0.3 * ema), or na if invalid
f_rank_and_select(scores, n)
Parameters:
scores (array) : Array of correlation scores
n (int) : Number of assets to select (typically 4)
Returns: Array of selected indices
f_is_self_reference(candidate_symbol, base_ticker)
Parameters:
candidate_symbol (string) : Full symbol string (e.g., "BINANCE:BTCUSDT")
base_ticker (string) : Base asset ticker (e.g., "BTC")
Returns: True if candidate is the base asset
f_route_scan_idx(idx, prices)
Parameters:
idx (int) : Index (0-9)
prices (array) : Array of 10 scan candidate prices
Returns: Price at index, or na if invalid
f_get_preset_basket(preset_name)
Parameters:
preset_name (string) : Name of preset ("Basket B (Memes)", etc.)
Returns:
f_get_default_scan_symbols()
f_calc_basket_fit(score1, score2, score3, score4)
Parameters:
score1 (float) : Correlation score of asset 1
score2 (float) : Correlation score of asset 2
score3 (float) : Correlation score of asset 3
score4 (float) : Correlation score of asset 4
Returns: Basket fit percentage (0-100)
f_get_fit_label(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Quality label ("Excellent", "Good", "Fair", "Poor")
f_get_fit_color(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Color (lime, aqua, orange, red)
ScanCandidate
Fields:
symbol (series string)
price (series float)
return_1bar (series float)
correlation_raw (series float)
correlation_ema (series float)
score (series float)
is_self (series bool)
BasketSelection
Fields:
sym1 (series string)
sym2 (series string)
sym3 (series string)
sym4 (series string)
score1 (series float)
score2 (series float)
score3 (series float)
score4 (series float)
idx1 (series int)
idx2 (series int)
idx3 (series int)
idx4 (series int) Library

kNNLib with turboQuant encodingLibrary "kNNLib"
f_quantize_3bit(value, bounds)
Quantize a single feature to 3-bit index (0-7) using percentile boundaries
Parameters:
value (float) : Feature value to quantize
bounds (array) : Array of 9 percentile boundaries
Returns: Integer index 0-7
f_compute_percentile_bounds(feature_array, history_len)
Compute percentile boundaries for a feature over a rolling window
Parameters:
feature_array (array) : Array of feature values (size = history_len)
history_len (int) : Number of bars to use for percentile calculation
Returns: Array of 9 boundaries
f_turboquant_encode(f1, f2, f3, f4, f5, f6)
Encode 6 features into 18-bit TurboQuant state ID
Parameters:
f1 (int) : Feature 1 (VectorOsc) quantized index 0-7
f2 (int) : Feature 2 (BasketCorr) quantized index 0-7
f3 (int) : Feature 3 (InnovZ) quantized index 0-7
f4 (int) : Feature 4 (TE_Osc) quantized index 0-7
f5 (int) : Feature 5 (OrthoZcvb) quantized index 0-7
f6 (int) : Feature 6 (PhiDiv) quantized index 0-7
Returns: 18-bit state ID (0 to 262143)
f_normalize_basket_corr(rho, rho_history, norm_len)
Normalize BasketCorr using Fisher transform then z-score
Parameters:
rho (float) : Raw correlation value
rho_history (array) : Array of historical rho values
norm_len (int) : Normalization window length
Returns: Normalized correlation
f_normalize_te_osc(te_osc, te_history, norm_len)
Normalize TE_Osc using rolling z-score
Parameters:
te_osc (float) : Raw TE oscillator value
te_history (array) : Array of historical TE values
norm_len (int) : Normalization window length
Returns: Normalized TE
f_normalize_phi_div(phi_div, phi_history, norm_len)
Normalize PhiDiv using rolling z-score
Parameters:
phi_div (float) : Raw PhiDiv value
phi_history (array) : Array of historical PhiDiv values
norm_len (int) : Normalization window length
Returns: Normalized PhiDiv
f_euclidean_distance(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_hist, f2_hist, f3_hist, f4_hist, f5_hist, f6_hist)
Calculate Euclidean distance between two 6D feature vectors
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_hist (float) : Historical bar feature 1
f2_hist (float) : Historical bar feature 2
f3_hist (float) : Historical bar feature 3
f4_hist (float) : Historical bar feature 4
f5_hist (float) : Historical bar feature 5
f6_hist (float) : Historical bar feature 6
Returns: Euclidean distance
f_find_k_nearest(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_history, f2_history, f3_history, f4_history, f5_history, f6_history, k, max_history)
Find K nearest neighbors using linear scan
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_history (array) : Array of historical feature 1 values
f2_history (array) : Array of historical feature 2 values
f3_history (array) : Array of historical feature 3 values
f4_history (array) : Array of historical feature 4 values
f5_history (array) : Array of historical feature 5 values
f6_history (array) : Array of historical feature 6 values
k (int) : Number of neighbors to find
max_history (int) : Maximum bars to search
Returns: Array of K nearest neighbor indices
f_calculate_confidence(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_history, f2_history, f3_history, f4_history, f5_history, f6_history, k_nearest_indices)
Calculate epistemic confidence score from K-nearest distances
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_history (array) : Array of historical feature 1 values
f2_history (array) : Array of historical feature 2 values
f3_history (array) : Array of historical feature 3 values
f4_history (array) : Array of historical feature 4 values
f5_history (array) : Array of historical feature 5 values
f6_history (array) : Array of historical feature 6 values
k_nearest_indices (array) : Array of K nearest neighbor indices
Returns: Confidence score Library

FO_UtilLibrary "FO_Util"
f_inSession(startHour, startMinute, endHour, endMinute)
Parameters:
startHour (int)
startMinute (int)
endHour (int)
endMinute (int)
f_isExecutionBlocked(marketType)
Parameters:
marketType (string)
f_allowEntry(useSessionFilter, startHour, startMinute, endHour, endMinute, marketType)
Parameters:
useSessionFilter (bool)
startHour (int)
startMinute (int)
endHour (int)
endMinute (int)
marketType (string)
f_volFilter(_volume, volMA, volMultiplier)
Parameters:
_volume (float)
volMA (float)
volMultiplier (float)
f_wickCondition(_open, _close, _high, _low, _ratio, _wickSide)
Parameters:
_open (float)
_close (float)
_high (float)
_low (float)
_ratio (float)
_wickSide (int)
f_atrRangeFilter(_high, _low, _atr, _mult)
Parameters:
_high (float)
_low (float)
_atr (float)
_mult (float)
f_updatePositionExtremes(inLong, inShort, prevHigh, prevLow, highestPrev, lowestPrev)
Parameters:
inLong (bool)
inShort (bool)
prevHigh (float)
prevLow (float)
highestPrev (float)
lowestPrev (float)
f_calcATRExitLevels(avgPrice, atr, atrStopMult, atrLimitMult)
Parameters:
avgPrice (float)
atr (float)
atrStopMult (float)
atrLimitMult (float)
f_calcATRTrailStop(avgPrice, highestPrev, lowestPrev, atrPrev, trailAtrMult, atrLimitMult, atrStopMult, inLong, inShort)
Parameters:
avgPrice (float)
highestPrev (float)
lowestPrev (float)
atrPrev (float)
trailAtrMult (float)
atrLimitMult (float)
atrStopMult (float)
inLong (bool)
inShort (bool)
f_calcATRExit(avgPrice, atr, highestPrev, lowestPrev, prevHigh, prevLow, trailAtrMult, atrStopMult, atrLimitMult, inLong, inShort)
Parameters:
avgPrice (float)
atr (float)
highestPrev (float)
lowestPrev (float)
prevHigh (float)
prevLow (float)
trailAtrMult (float)
atrStopMult (float)
atrLimitMult (float)
inLong (bool)
inShort (bool)
f_executeEntry(longSignal, shortSignal)
Parameters:
longSignal (bool)
shortSignal (bool)
f_isPreClose(closeHour, closeMinute)
Parameters:
closeHour (int)
closeMinute (int)
f_executeSessionClose(useSessionClose, closeHour, closeMinute)
Parameters:
useSessionClose (bool)
closeHour (int)
closeMinute (int) Library

BOT_1_0_LIB_TEXTLibrary "BOT_1_0_LIB_TEXT"
f_b01(b)
Parameters:
b (bool)
f_na_raw(x)
Parameters:
x (float)
f_na2(x)
Parameters:
x (float)
f_na4(x)
Parameters:
x (float)
f_panel_m01_detail(tBaseL, tBaseS, tDeltaL, tDeltaS, tSlopeL, tSlopeS, tDeltaUsed)
Parameters:
tBaseL (bool)
tBaseS (bool)
tDeltaL (bool)
tDeltaS (bool)
tSlopeL (bool)
tSlopeS (bool)
tDeltaUsed (float)
f_panel_m02_detail(cHtfUp, cHtfDown, cAdxOk, cAtrOk)
Parameters:
cHtfUp (bool)
cHtfDown (bool)
cAdxOk (bool)
cAtrOk (bool)
f_panel_m05_detail(m05DetView, m05_state, m05_cnt, m05ConfirmPulse, useConf)
Parameters:
m05DetView (string)
m05_state (int)
m05_cnt (int)
m05ConfirmPulse (bool)
useConf (bool)
f_panel_m06_detail(m06_mode, m06_trigger, m06pBarsLeftTxt, m06pMinLeftTxt, useCD)
Parameters:
m06_mode (string)
m06_trigger (string)
m06pBarsLeftTxt (string)
m06pMinLeftTxt (string)
useCD (bool)
f_panel_m07_det1(cycleTxt, entry, sl, tp, gate, gateEvent, killReason, killAge, useM07)
Parameters:
cycleTxt (string)
entry (float)
sl (float)
tp (float)
gate (bool)
gateEvent (bool)
killReason (string)
killAge (float)
useM07 (bool)
f_panel_m07_det2(evScoreL, evScoreS, evThrFinalL, evThrFinalS, evThrRegL, evThrRegS, uqNovelL, uqNovelS, evtNovelL, evtNovelS, m06_canTrade, m07_sigPulse, useM07)
Parameters:
evScoreL (float)
evScoreS (float)
evThrFinalL (float)
evThrFinalS (float)
evThrRegL (float)
evThrRegS (float)
uqNovelL (bool)
uqNovelS (bool)
evtNovelL (bool)
evtNovelS (bool)
m06_canTrade (bool)
m07_sigPulse (bool)
useM07 (bool)
f_panel_m03_detail(stateTxt, sideTxt, regraAtiva, reqAntesArm)
Parameters:
stateTxt (string)
sideTxt (string)
regraAtiva (string)
reqAntesArm (int)
f_panel_perf_detail(perfCumR, perfAvgR, perfAvgWin, perfAvgLoss, perfPayoff, perfExpectancyPanel, perfBestTradeR, perfWorstTradeR, perfWinStreak, perfBestWinStreak, perfLossStreak, perfBestLossStreak)
Parameters:
perfCumR (float)
perfAvgR (float)
perfAvgWin (float)
perfAvgLoss (float)
perfPayoff (float)
perfExpectancyPanel (float)
perfBestTradeR (float)
perfWorstTradeR (float)
perfWinStreak (int)
perfBestWinStreak (int)
perfLossStreak (int)
perfBestLossStreak (int)
f_panel_perf_last_detail(perfLastTradeR, perfLastTradeReason, perfActiveTradeId, perfCycleCumR)
Parameters:
perfLastTradeR (float)
perfLastTradeReason (string)
perfActiveTradeId (int)
perfCycleCumR (float)
f_panel_flow_state_detail(flowDiag_win, flowDiag_followBars, flowDiag_hostileX)
Parameters:
flowDiag_win (int)
flowDiag_followBars (int)
flowDiag_hostileX (int)
f_panel_flow_cnt_long(flowDiag_cCount, flowDiag_gCount)
Parameters:
flowDiag_cCount (int)
flowDiag_gCount (int)
f_panel_flow_cnt_short(flowDiag_pCount, flowDiag_xCount)
Parameters:
flowDiag_pCount (int)
flowDiag_xCount (int)
f_panel_flow_cnt_detail(flowDiag_friction, flowDiag_gFailedCount)
Parameters:
flowDiag_friction (float)
flowDiag_gFailedCount (int)
f_panel_flow_cont_detail(m07_cfSlopeNow, ac_widthPct)
Parameters:
m07_cfSlopeNow (float)
ac_widthPct (float)
f_panel_edge_sig_detail(edgeGlobalClass, edgeFollowRate, edgeTotal)
Parameters:
edgeGlobalClass (string)
edgeFollowRate (float)
edgeTotal (int)
f_panel_edge_cnt_long(edgeFollowCount, edgeNeutralCount, edgeFailCount)
Parameters:
edgeFollowCount (int)
edgeNeutralCount (int)
edgeFailCount (int)
f_panel_edge_cnt_short(traceEdgeMinSamples, traceEdgeGoodRate)
Parameters:
traceEdgeMinSamples (int)
traceEdgeGoodRate (float)
f_panel_edge_cnt_detail(traceEdgeWindowBars, traceEdgeStrongR, traceEdgeFailR)
Parameters:
traceEdgeWindowBars (int)
traceEdgeStrongR (float)
traceEdgeFailR (float)
f_panel_edge_reg_short(follow, neutral, fail)
Parameters:
follow (int)
neutral (int)
fail (int)
f_panel_edge_rate_detail(rate)
Parameters:
rate (float)
f_panel_edge_acc_detail(traceEdgeAccelMode, edgeAccelRate)
Parameters:
traceEdgeAccelMode (string)
edgeAccelRate (float) Library

FootprintCore
ExperimentaL WIP
The FootprintCore library is a Pine Script v6 toolset designed for deep analysis of order flow and footprint data. It provides structured data types and functions to extract, normalize, and interpret footprint features to identify market breakouts and execution regimes.
Core Data Types
FPBar: Captures raw footprint metrics including volume (total, buy, sell), Delta, POC/Value Area levels, and imbalance stack counts.
FPNorm: Stores normalized versions of key features, primarily using Z-Scores and Percentile Ranks to compare current activity against historical lookbacks.
FPDerived: Holds high-level interpretations such as "Stack Dominance," "Bullish Acceptance," and "Auction Failures".
FPSignal & FPExec: Define trade triggers and execution states (e.g., passive, caution, or avoid) based on current volatility and liquidity.
How to Use the Library
1. Feature Extraction
Use extractBar() to convert a footprint object into a structured FPBar type. You must provide price context (close, high, low) and an ATR value for normalization.
Pine Script
fp_data = footprint.get()
bar_features = FootprintCore.extractBar(fp_data, prevPoc, close, high, low, ta.atr(14))
2. Normalization
Pass the FPBar into normalizeBar() to calculate Z-Scores and Ranks for features like Value Area width and Delta efficiency.
Pine Script
norm_features = FootprintCore.normalizeBar(bar_features, 20, 100)
3. Generating Signals
The breakoutSignal() function identifies high-probability trade setups. It checks for:
Bullish/Bearish Acceptance: Price breaking out of the Value Area with positive/negative Delta.
+1
Stack Dominance: Presence of imbalance stacks (e.g., more than 3 buy stacks).
Efficiency: Delta efficiency and range compression requirements.
+1
4. Execution Governance
Before placing a trade, use executionState() to assess the "stress" of the current market.
ExecMode.avoid: Triggered when slippage proxies or fragility scores (based on Z-Scores) are too high.
+1
noTrade: A boolean flag that becomes true if footprint data is missing or the market structure is unstable.
5. Diagnostic Reason Codes
For debugging or logging, reasonCodeBreakout() returns a machine-readable string (e.g., "ACC|STACK|EFF|") indicating which specific conditions were met for a signal.
Library

FpFeaturesLibrary "FpFeatures"
buyStackCount(rows)
Parameters:
rows (array)
sellStackCount(rows)
Parameters:
rows (array)
maxRowDeltas(rows)
Parameters:
rows (array)
pocMid(fp)
Parameters:
fp (footprint)
pocShift(fp, prevPocMid)
Parameters:
fp (footprint)
prevPocMid (float)
vaWidthPct(fp, close_)
Parameters:
fp (footprint)
close_ (float)
deltaEfficiency(fp)
Parameters:
fp (footprint)
topTailUnfinished(fp, minSideVol)
Parameters:
fp (footprint)
minSideVol (float)
bottomTailUnfinished(fp, minSideVol)
Parameters:
fp (footprint)
minSideVol (float)
acceptanceAboveVAH(fp, close_, high_, low_, frac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
frac (float)
acceptanceBelowVAL(fp, close_, high_, low_, frac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
frac (float)
compute(fp, close_, high_, low_, prevPocMid, minTailSideVol, acceptanceFrac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
prevPocMid (float)
minTailSideVol (float)
acceptanceFrac (float)
FeatureSet
Fields:
buyStackCount (series int)
sellStackCount (series int)
maxPosRowDelta (series float)
maxNegRowDelta (series float)
topTailUnfinished (series bool)
bottomTailUnfinished (series bool)
pocMid (series float)
pocShift (series float)
vaWidthPct (series float)
deltaEfficiency (series float)
acceptanceAboveVAH (series bool)
acceptanceBelowVAL (series bool) Library

Library

MLLibLibrary "MLLib"
Machine Learning Library - Adaptive learning algorithms for parameter optimization
f_kirschenbaum_sgd(feature_z, baseline_ma, baseline_dev, pivot_high, pivot_low, sensitivity_current, learning_rate, sensitivity_min, sensitivity_max, coupling_strength, coupling_gate, pivot_lookback, proximity_pct, survival_prob)
Pivot-based SGD for adaptive sensitivity tuning (Kirschenbaum method)
Parameters:
feature_z (float) : Z-score of the predictive feature (e.g., basket vector)
baseline_ma (float) : Baseline moving average (center line)
baseline_dev (float) : Standard deviation for band calculation
pivot_high (float) : Recent pivot high price (na if none)
pivot_low (float) : Recent pivot low price (na if none)
sensitivity_current (float) : Current sensitivity parameter value
learning_rate (float) : Learning rate for SGD updates
sensitivity_min (float) : Minimum allowed sensitivity value
sensitivity_max (float) : Maximum allowed sensitivity value
coupling_strength (float) : Coupling strength for gating updates (0-1)
coupling_gate (float) : Minimum coupling threshold for updates
pivot_lookback (int) : Lookback period to historical feature/price at pivot
proximity_pct (float) : Proximity threshold (0-1) for pivot to be "near band"
survival_prob (float) : Survival probability for band calculation (e.g., 0.68 for 1-sigma)
Returns: Updated sensitivity and number of updates performed
f_sgd_update(param_current, gradient, learning_rate, param_min, param_max, gate_strength, gate_threshold)
Generic SGD parameter update with optional gating
Parameters:
param_current (float) : Current parameter value
gradient (float) : Gradient (error * feature)
learning_rate (float) : Learning rate
param_min (float) : Minimum parameter value
param_max (float) : Maximum parameter value
gate_strength (float) : Gating strength (0-1, optional)
gate_threshold (float) : Minimum gate strength to allow full update
Returns: float Updated parameter value
SGDState
SGD learning state for tracking parameter updates
Fields:
param (series float) : Current parameter value
updates (series int) : Number of updates performed
last_error (series float) : Last prediction error Library

Library
