PINE LIBRARY

DafeRCMLib

923
Rolling 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:

Pine Script®
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:

  1. Price below the anchor (+1.5)
  2. Bear impulse condition detected (+1.0)
  3. Upper wick ratio exceeds 35% (+0.75)
  4. Anchor slope is negative (+1.0)
  5. Bear pressure exceeds 45% (+1.0)
  6. Close and high are both lower than previous bar (+0.75)
  7. 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.

Pine Script®
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
Pine Script®
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
Pine Script®
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):

Pine Script®
band := band * rcm.get_band_mod(st, 0.45, 1.10)


For score-based systems (signal scoring, ML models):

Pine Script®
fusedScore = rawScore + rcm.get_score_mod(st, rawScore, 0.25)


For signal gating:

Pine Script®
buySignal := buySignal and rcm.get_gate(st, true)


For directional permissions:

Pine Script®
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
Pine Script®
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
Pine Script®
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
Pine Script®
[regimeTxt, regimeCol] = rcm.narrative_regime(st, bullCol, bearCol, transCol, dimCol) [kinTxt, kinCol] = rcm.narrative_kinetics(st, accentCol, dimCol) [structTxt, structCol] = 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.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.