OPEN-SOURCE SCRIPT
Mis à jour

Consensus Oscillator (Algionics) - Volume Profile Oscillator

2 101
Consensus Oscillator converts the Consensus Band engine into a normalized oscillator. Instead of reading levels on the price chart, you read a single line that tells you where price sits within the volume-derived band structure.

This indicator runs on the same spectral-weighted volume profile engine as Consensus Band. 236-bar lookback, 28-line ribbon weighting, log-price space, parabolic-interpolated VPOC, and sigma-derived Consensus Area and Boundary Band. Every structure is shared.

From the five outputs the engine produces (VPOC, CA-H, CA-L, BB-H, BB-L), the oscillator maps price position onto a fixed scale. Zero marks the anchor. Plus or minus 25 marks the Consensus Area edges. Plus or minus 50 marks the Boundary Band edges. The scale is fixed, but the price levels behind it are not. They shift with every bar as the volume distribution evolves.


Three Modes
  • VPOC mode anchors the oscillator to the Volume Point of Control.
  • CA-M mode anchors it to the geometric midpoint of the Consensus Area.
  • Consensus mode runs both anchors simultaneously and applies a coherence filter. When both anchors agree on direction with similar magnitude, the output passes through. When they conflict, the output compresses toward zero. This is not an average. It is a gated output that only fires when two independent anchors confirm each other.



The Scale
Zero is the anchor price. Positive values mean price is above it, negative values mean below. Plus or minus 25 marks the Consensus Area edges. Plus or minus 50 marks the Boundary Band edges.

Between 0 and plus or minus 25, price is inside the Consensus Area. Between plus or minus 25 and plus or minus 50, price has left the consensus zone but remains within the statistical boundary. Beyond plus or minus 50, price is extended past plus or minus 2 sigma of the weighted volume distribution.

The normalization is asymmetric. The distance from the anchor to CA-H is treated independently from the distance to CA-L. Each side scales on its own, so the reading reflects true proportional position rather than assuming the distribution is symmetric.


Slow Line
The Slow line smooths the oscillator output. Three period options are available, all derived from the ribbon parameters. The derivation in code:
Pine Script®
int SMOOTH_LEN = int(math.round(math.sqrt(float(RB_MAX)))) int HM_LEN = int(math.round(2.0 * float(RB_START) * float(RB_MAX) / float(RB_START + RB_MAX))) int GM_LEN = int(math.round(math.sqrt(float(RB_START) * float(RB_MAX))))

SMOOTH_LEN is the square root of the ribbon maximum period. In signal processing, the square root of a window length defines the natural smoothing horizon where noise suppression begins without distorting the underlying structure.

HM_LEN is the harmonic mean of the ribbon endpoints. It weights toward the shorter period. In physics, the harmonic mean governs systems where rates combine in parallel: electrical resistance, lens focal lengths, reduced mass in orbital mechanics. Here it represents the natural interaction period between the shortest and longest temporal scales of the ribbon.

GM_LEN is the geometric mean. It sits at the multiplicative midpoint between the two endpoints, equidistant in ratio space. It captures the broadest structural trend the ribbon can resolve without exceeding its own temporal range.

Three perspectives on the same constant pair. No period was chosen because it looked right on a chart.

When the oscillator crosses above the Slow line, momentum is shifting upward relative to its own average. When it crosses below, momentum is fading.


Fill
When Show Fill is enabled, gradient shading appears between the oscillator line and the zero line. The fill uses bull color above zero and bear color below, fading toward zero.


Price Candles
When enabled, price candles on the main chart are colored using the sigma-position gradient. Each candle's color reflects where the close sits within the band structure, shifting from bear color at the lower boundary to bull color at the upper boundary.


Anchor Overlay
The Anchor line draws the active anchor price directly on the main chart. In VPOC mode it shows the VPOC, in CA-M mode it shows the Consensus Area midpoint, and in Consensus mode it shows the geometric mean of both.

When Anchor Gradient is enabled, the line color shifts based on sigma-position. When disabled, the line uses a fixed neutral color.


Technical Implementation

236-Bar Lookback, Zero Lag
A 236-bar lookback sounds like it should produce severe lag. It does not. The reason is the spectral weight function.

In a simple moving average, every bar in the window contributes equally. The center of mass sits at bar 118, meaning the output structurally lags by 118 bars. In an EMA, the center of mass shifts toward the present but remains a fixed fraction of the period.

The spectral weight curve is neither. The weight array construction logic:
Pine Script®
for i = 0 to RB_MAX - 1 int count = 0 for k = 0 to RB_COUNT - 1 if i < RB_START + RB_STEP * k count += 1 array.set(w_arr, i, float(count) / float(RB_COUNT))

For each bar index i, the loop counts how many ribbon lines have a period greater than i, then divides by the total number of lines. At bar 0 (current), all 28 lines cover it. At bar 19, 27 of 28 lines still cover it. At bar 100, 17 of 28 lines cover it. At bar 235, only the longest line covers it.

The center of mass of this curve sits at approximately bar 42, not bar 118. Over 70 percent of the total weight is concentrated in the first 80 bars. The remaining 156 bars contribute structural memory without dragging the response.

The EMA smoothing applied to the five outputs uses SMOOTH_LEN, derived as sqrt(RB_MAX). It is the characteristic smoothing scale of the window itself. It suppresses single-bar noise without adding perceptible delay to a structure whose center of mass already sits near the present.

The result: a system that sees 236 bars of history but responds as if it sees 40.


Spectral Decay Weighting
Standard volume profiles apply a rectangular window function: every bar inside the lookback counts equally, every bar outside counts zero. One bar crossing that boundary triggers a full profile reconstruction.

This engine replaces the rectangular window with a spectral decay envelope derived from the ribbon structure. RB_COUNT layers spanning RB_START to RB_MAX form the decay curve. Each bar's volume contribution is weighted by its ribbon coverage ratio, producing a smooth monotonic rolloff with no discontinuity. The resulting profile evolves continuously rather than jumping between discrete states.


Logarithmic Price-Space Rasterization
The volume profile grid is rasterized in log-price coordinates. Each row spans an equal multiplicative interval, not an equal additive interval.
Pine Script®
float logMin = math.log(canvas_low) float logMax = math.log(canvas_high) float logRange = logMax - logMin float logStep = logRange / ROW_SIZE

A 5 percent displacement maps to identical row coverage whether the instrument trades at 10 or 10,000. Linear rasterization compresses lower price ranges and inflates upper ranges, distorting both the VPOC location and the sigma boundaries. Log-space eliminates this bias entirely.


O(N+R) Prefix-Sum Profile Construction
The volume profile grid is constructed via a differential accumulation array. The core logic:
Pine Script®
for i = 0 to math.min(RB_MAX - 1, maxIdx) int rStart = int((lL - logMin) / logStep) int rEnd = int((lH - logMin) / logStep) float addv = v_r * array.get(w_arr, i) array.set(diff, rStart, array.get(diff, rStart) + addv) array.set(diff, rEnd + 1, array.get(diff, rEnd + 1) - addv) float run = 0.0 for r = 0 to ROW_SIZE - 1 run += array.get(diff, r) array.set(vol_master, r, run)

For each bar in the lookback, only two array writes mark the start and end of its log-price range. A single prefix-sum sweep then converts the difference array into the complete volume histogram. Total complexity per bar: O(N + R) where N is the lookback depth and R is the grid resolution. This avoids the O(N x R) brute-force approach and enables high-resolution profiles to rebuild on every bar without frame-rate degradation.


Sub-Row VPOC via Parabolic Interpolation
Row-based volume profiles quantize the VPOC to the nearest grid boundary, introducing staircase artifacts proportional to 1/ROW_SIZE. The interpolation logic:
Pine Script®
if poc_idx > 0 and poc_idx < sz - 1 float v_up = array.get(v_arr, poc_idx + 1) float v_dn = array.get(v_arr, poc_idx - 1) float local_sum = v_up + v_dn + max_v if local_sum > 0 precise_idx := ((poc_idx - 1) * v_dn + poc_idx * max_v + (poc_idx + 1) * v_up) / local_sum

The volume at the peak row and its two immediate neighbors serves as weights to compute a continuous sub-row centroid. The result is a smooth VPOC trajectory free of quantization noise, even at moderate grid resolutions.


Piecewise Asymmetric Normalization
Conventional oscillators (RSI, Stochastic, CCI) impose symmetric scaling around a midpoint, assuming equal distance to overbought and oversold boundaries. Real volume distributions are rarely symmetric. The normalization function:
Pine Script®
f_normalize(float val, float anchor, float _caH, float _caL, float _bbH, float _bbL) => if val >= _caH 25.0 + ((_bbH - _caH) > 0 ? ((val - _caH) / (_bbH - _caH)) * 25.0 : 0.0) else if val >= anchor (_caH - anchor) > 0 ? ((val - anchor) / (_caH - anchor)) * 25.0 : 0.0 else if val >= _caL (anchor - _caL) > 0 ? ((val - anchor) / (anchor - _caL)) * 25.0 : 0.0 else -25.0 + ((_caL - _bbL) > 0 ? ((val - _caL) / (_caL - _bbL)) * 25.0 : 0.0)

Anchor to CA edge normalizes to 0 through plus or minus 25. CA edge to BB edge normalizes to plus or minus 25 through plus or minus 50. Each half-plane scales independently against its own span, preserving the native asymmetry of the underlying distribution on every bar.


Dual-Anchor Coherence Gating
The core logic of Consensus mode:
Pine Script®
float direction = (oscillator + osc_cam) * 0.5 float denom = oscillator * oscillator + osc_cam * osc_cam float coherence = denom > 0 ? (2.0 * oscillator * osc_cam) / denom : 0.0 float unified = direction * coherence float filtered = coherence > 0 ? unified : 0.0

The coherence coefficient C = 2ab / (a squared + b squared) is a normalized inner-product metric borrowed from signal coherence analysis in communications engineering. When both anchors align (C approaches 1), the directional average passes at full amplitude. When they diverge (C approaches 0), the output is suppressed toward zero. This is not averaging. It is multiplicative gating that rejects incoherent regimes.


Interlocking Constant Architecture
From these three constants the ribbon structure is defined, and from that ribbon: lookback weights, smoothing length, all three Slow periods, profile canvas boundaries, band derivation, and VPOC precision are all derived. Change one constant and the entire downstream chain recalculates. Widen the ribbon step and the weight curve reshapes, the smoothing lengths shift, the slow periods rebalance, and the band dynamics respond differently. Every gear turns every other gear. There is no isolated parameter to tune without consequence.

This is by design. A system where one piece can be adjusted without affecting the rest is a system where the pieces were never truly connected. Here, mathematical coherence is structural. If you modify the ribbon, you are modifying everything. Approach customization with the same rigor the system was built with, or the architecture works against you instead of for you.


Incremental Realtime Computation
When the indicator ran on a live chart for extended periods, the realtime bar triggered a full profile rebuild on every incoming tick. Over time this accumulated enough computation to hit the execution limit and crash the script.

Two changes were made. First, the cache that stores historical bar data was pushing duplicate entries on every realtime tick instead of updating the current bar in place. After hours of live operation, this gradually displaced confirmed historical bars from the lookback window, degrading profile accuracy without any visible warning. The cache now only writes on confirmed bars, preserving the full lookback integrity.

Second, the profile build logic was restructured. On confirmed bars, a full rebuild runs once and the result is stored as a stable base. On realtime ticks, the base is reused and only the current bar's contribution is applied incrementally. If the price canvas shifts due to a new high or low in the lookback range, a full rebuild is triggered automatically to keep the grid mapping consistent.

No changes were made to the oscillator logic, normalization, coherence, or any output calculation.


Settings
Profile Resolution (500 to 1000): controls the granularity of the volume profile grid. Higher values produce finer detail.

Mode: selects the oscillator anchor. VPOC measures position relative to the Volume Point of Control. CA-M measures position relative to the Consensus Area midpoint. Consensus applies a coherence filter that only passes output when the two anchors agree.

Show Fill: toggles gradient shading between the oscillator line and the zero line.

Show Slow / Slow Period: toggles the smoothed reference line and selects its period. Fast uses sqrt(RB_MAX). Medium uses the harmonic mean. Slow uses the geometric mean.

Price Candles: colors candles on the main chart using the sigma-position gradient.

Show Anchor Line / Anchor Gradient: draws the active anchor price on the main chart and shifts its color based on sigma-position.
Notes de version
Updated code header documentation. No changes to indicator logic, normalization, coherence, or any output calculation.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.