KF_ANALYTICSKF-ANALYTICS™ — Analytics Services™ library for THE KINGFISHER™ architecture.
Provides the constitutional analytics layer, including analytics identity, canonical constants, enumerations, runtime contracts, deterministic utility functions, manifest governance, engineering standards, health monitoring, diagnostics, and consolidated analytics summaries.
Designed as a modular, deterministic, non-executive analytics foundation for the wider THE KINGFISHER™ ecosystem. Library

Indicator

TrueMove: Council of 7 Schools [TechnicalZen]A Decision Support System for Risk Management.
Imagine seven analysts — each a specialist in a different discipline — studying the same price chart simultaneously. One reads volume flow. Another scores multi-factor confluence. A third measures Wyckoff effort dynamics. A fourth compares wave speed and amplitude. A fifth tracks volume-weighted momentum. A sixth applies adaptive Kalman filtering. A seventh learns patterns from the instrument's own history using machine learning. Each arrives at their own independent conclusion. Then they vote.
This is what this indicator does. Seven academically grounded analytical Schools, each examining price action through a fundamentally different lens, casting independent votes on market direction. The result is not a prediction — it is a decision support system designed to help traders manage risk with confidence.
The core question it answers: "Is this move real, or is it a trap?"
When the council reaches consensus, you trade with conviction. When it doesn't, you wait. The strength of this system is not in any single School — it is in the convergence of independent perspectives. A move confirmed by volume flow, momentum, wave dynamics, and machine learning simultaneously carries fundamentally different weight than a move flagged by one method alone.
This is risk management through structured consensus. Not a black box. Not a single signal line. A council of seven independent minds, each with a transparent methodology, each with a tracked hit rate, each accountable for its calls.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The System
The indicator operates on three layers:
Signal Layer — Seven independent Schools analyze price action using different methodologies. Each votes Bull or Bear when its conditions are met.
Council Layer — Votes are aggregated. In "2+ Agree" mode, a signal fires only when two or more Schools vote in the same direction within a 3-bar window. In "All Signals" mode, any School's vote fires a signal.
Visual Layer — POC lines (anchored VWAP), EVWAP (exponentially weighted VWAP), risk/reward boxes, and direction labels present the council's verdict on the price chart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Council
The council aggregates school votes using a configurable consensus mechanism:
"2+ Agree" Mode — Requires two or more enabled Schools to vote in the same direction within a 3-bar window. This is the conservative mode. Fewer signals, higher conviction. If only one School is enabled, it automatically drops to requiring just that one vote.
"All Signals" Mode — Any enabled School's vote fires a signal. This is the aggressive mode. More signals, lower filtering. Useful for seeing what each School detects independently.
Conflict Resolution — If bull and bear votes arrive on the same bar, the direction with more votes wins. If tied, bull wins (consistent tie-breaking).
Cooldown — Separate bull and bear cooldowns prevent signal spam in the same direction while allowing quick reversals when the market genuinely flips.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The 7 Schools
Each School uses a fundamentally different analytical approach. They are designed to be independent — a signal from one School does not depend on or duplicate another.
School 1: OBV Flow
What it sees: Volume flow divergence and acceleration
Detects when On-Balance Volume diverges from price (hidden buying or selling pressure) and when volume flow is accelerating in a direction supported by market structure.
School 2: Confluence
What it sees: Multi-factor agreement across independent indicators
Triggers when RSI exits oversold (bull) or crosses below the momentum midline (bear) in a trending market. Scores seven independent factors and requires four or more to agree.
School 3: Wyckoff
What it sees: Effort vs Result on pullbacks, plus trap events
Measures whether pullback volume is declining relative to pre-pullback volume (Wyckoff effort), whether the bounce bar shows commitment (result), and detects Spring and Upthrust events — false breakdowns and breakouts that trap weak hands.
School 4: Amplitude Strength
What it sees: Wave dynamics — speed, time, and volume at swing points
Compares consecutive swing waves: is the trend wave faster than the pullback? Is the pullback shorter in time? Is volume declining at successive swing lows (or highs)? Is momentum oversold (or overbought) at the swing point? Scores seven wave-quality factors.
School 5: VWMA Delta
What it sees: Volume-weighted momentum crossing fair value
Computes the difference between short-term and long-term Volume Weighted Moving Averages, smooths it with RMA, and fires when this delta crosses zero. Volume is built into the measurement itself — not added as a secondary filter.
School 6: Kalman Filter (LQE)
What it sees: Adaptive filtered trend crossover
Applies two Kalman filters (Linear Quadratic Estimator) to price at different speeds. The short filter crossing above or below the long filter signals a trend shift. The Kalman filter adapts its responsiveness automatically based on estimation uncertainty.
School 7: Naive Bayes (Adaptive)
What it sees: Learned patterns in raw price action DNA
A machine learning classifier that observes six raw features no other School uses: body trend, wick dominance, price percentile, volatility regime, momentum acceleration, and gap behavior. It builds Gaussian probability profiles from resolved outcomes and votes when its confidence exceeds 65% in either direction. This School learns and adapts to the specific instrument and timeframe over time.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
School Rules — Complete Reference
School 1: OBV Flow (5 rules)
Price at/near 20-bar low (within 5% of range) — bull trigger
OBV well above its 20-bar low (>15% of OBV range) — divergence detection
OBV above its SMA(20) — volume flow trend confirmation
OBV slope accelerating (current 5-bar slope > previous) — momentum
Bull structure (higher lows) confirmed — structural context
Bear: symmetric mirror of all conditions
School 2: Confluence (9 rules — 2 trigger + 7 scored, need 4/7)
Trigger: RSI crosses above 30 (bull) or below 50 (bear)
Trigger gate: ADX ≥ 20 + price on correct side of EMA
Score: ADX ≥ 25 (strong trend)
Score: Bull/bear structure confirmed
Score: Price above/below SMA(50) (longer-term trend alignment)
Score: MACD line vs signal agreement
Score: Price touched EMA in last 2 bars (level test)
Score: Volume above average
Score: Candle body ratio > 50%
School 3: Wyckoff (9 rules — 7 standard + 2 trap events)
EMA cross initiates pullback tracking
Pullback duration ≥ 3 bars
Average pullback volume < pre-pullback average volume (declining effort)
OR average body ratio < 0.45 during pullback (narrow bars)
Bounce bar body ratio > 50% (strong commitment)
Bounce bar volume > pullback average volume (expanding effort)
EMA cross back confirms resolution
Spring: price breaks below previous swing low, closes back above with volume
Upthrust: price breaks above previous swing high, closes back below with volume
School 4: Amplitude Strength (7 scored, need 4/7)
Bull/bear structure confirmed
Trend wave amplitude > 0.8 ATR (bull: up-wave, bear: down-wave separately)
Trend wave speed > pullback speed (impulsive move, not grinding)
Pullback duration < trend wave duration (quick correction)
Current pullback shallower than previous (< 1.2x)
Current swing volume < previous swing volume (swing-to-swing comparison)
RSI < 40 at swing low (bull) / RSI > 60 at swing high (bear)
School 5: VWMA Delta (1 rule)
RMA(30) of VWMA(5) minus VWMA(30) crosses zero
School 6: Kalman Filter LQE (1 rule)
Kalman filter (length 50, R=0.01, Q=0.10) crosses above/below Kalman filter (length 100)
School 7: Naive Bayes Adaptive (6 features + confidence threshold)
Feature: 3-bar body trend (growing or shrinking candle bodies)
Feature: Wick dominance (upper vs lower wick ratio — rejection direction)
Feature: Price percentile in 20-bar range (position within recent range)
Feature: Volatility regime (ATR vs its SMA — expanding or contracting)
Feature: Momentum acceleration (bar-to-bar price change speeding up or slowing)
Feature: Gap behavior (open vs previous close, ATR-normalized)
Threshold: P(bull) ≥ 65% to vote bull, P(bull) ≤ 35% to vote bear
Requires minimum 15 resolved samples before voting
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How the Schools Differ
Schools 1 & 5 are volume-driven — they measure where money is flowing, not where price is moving.
Schools 2 & 4 are multi-factor scoring systems — they require multiple conditions to align before voting, reducing false positives.
School 3 is event-driven — it detects specific Wyckoff structural events (springs, upthrusts, effort exhaustion) rather than continuous measurements.
School 6 is filter-driven — it uses an adaptive mathematical estimator that adjusts its own responsiveness based on estimation uncertainty.
School 7 is the only School that learns — it builds its model from the instrument's own history and adapts over time. Every other School uses fixed rules.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Voting System
Each School votes independently. Votes are collected within a 3-bar window — Schools do not need to fire on the exact same bar to count as agreeing. This accommodates the fact that different analytical methods detect events at slightly different times.
The dashboard shows each School's most recent vote using directional emojis and colors the School name green (bull vote) or red (bear vote) when it participated in the last signal. Schools are sorted by recency — the most recently active School appears at the top of the list.
The Hit Rate column shows each School's accuracy when it participated in council signals — how often signals were correct when that School voted. This is not standalone accuracy; it measures performance within the council context.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
POC Lines (Anchored VWAP)
Three dashed lines that represent volume-weighted fair value since the last extreme volume event:
Center — the anchored VWAP: where volume-weighted price has centered since the last climax event
Upper and Lower — standard deviation bands that start at the same point as the center (origin) and branch outward as price disperses
The POC re-anchors when a volume extreme is detected (volume z-score exceeds the threshold with a directional candle). All three lines converge to a single origin point at the climax bar, then branch as the new VWAP accumulates data.
The line closest to price is highlighted with increased width and brightness. When the council signals a direction and price subsequently moves against it (crossing the POC center in the wrong direction for 3+ bars), the highlighted line changes color — red for a failed bull signal, green for a failed bear signal. This failure detection provides immediate visual feedback that the anticipated move did not materialize.
Hull smoothing can be applied to the POC lines for cleaner visual tracking.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EVWAP (Exponentially Weighted VWAP)
A solid line that tracks volume-weighted fair value with exponential decay, re-anchoring at swing direction changes:
Uses the same Exponentially Weighted Moving Average formula as the DS-VWAP methodology
Re-seeds at swing pivot points detected by the swing period setting
Volume spikes are capped at 3x the 20-bar average to prevent single bars from hijacking the calculation
Changes color based on swing direction — bull color when the most recent swing high is more recent, bear color when the most recent swing low is more recent
Direction change triangles mark where each new segment begins
Hull smoothing can be applied for a cleaner line.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Cyclic Structure: POC within EVWAP
The POC and EVWAP operate on different cycles and anchor to different events:
EVWAP re-anchors on swing direction changes (structural pivots in price). It represents the macro fair value — where the broader trend says price should be.
POC re-anchors on volume extreme events (climax bars). It represents the micro fair value — where volume clustered after the last burst of aggressive participation.
These cycles are not synchronized. A volume climax can happen mid-swing. A swing pivot can happen without a volume extreme. When both re-anchor near the same bar, that is a structurally significant event — both macro and micro fair value are resetting simultaneously.
The POC lines oscillate within the EVWAP framework. When the POC center is above the EVWAP line, volume-weighted activity is biased above the structural trend — bullish pressure. When below, bearish pressure. This relationship provides a dynamic reading of whether short-term volume activity agrees with the broader trend direction.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Risk/Reward Boxes
When a signal fires, two boxes are drawn:
Green box (above entry for bull, below for bear) — the take-profit zone at 2:1 risk-reward ratio
Red box (below entry for bull, above for bear) — the stop-loss zone at 0.5 ATR from the signal bar's extreme
Boxes extend 15 bars forward
Higher vote counts produce slightly more opaque boxes (stronger conviction = more visible)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Hit Rate and Accuracy Tracking
The indicator tracks signal accuracy using Maximum Favorable Excursion (MFE):
After each signal, the tracker monitors the next 12 bars
If price reaches 0.5 ATR in the signal direction at any point during those 12 bars (using the bar's high for bull signals, low for bear signals), the signal is marked correct
This is not a close-at-bar-12 check — it measures whether the move occurred , not whether it held
The dashboard displays:
Per-School Hit Rate — accuracy when that School participated in the council signal
Council Accuracy — overall accuracy across all evaluated signals
Signals — evaluated count vs total fired (signals during an active evaluation window are not double-counted)
Naive Bayes Learning — current status and class distribution of the adaptive learner
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Visual Aesthetics
The indicator is designed for visual clarity on dark-themed charts:
POC lines — dashed, in a distinct blue tone, with the tracked line highlighted at double width
EVWAP line — solid, colored by swing direction (bull/bear), with direction triangles at segment starts
Climax circles — small colored dots marking extreme volume events, no glow clutter
Signal labels — directional arrows with vote counts (e.g., "↑ Up (3/7)")
Dashboard — Schools sorted by recency of last vote, with bull/bear emojis and color-coded names. Schools that voted in the most recent signal appear at the top and light up in the direction color.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Council Behavior — "2+ Agree" (consensus) or "All Signals" (any School)
Signal Cooldown — Minimum bars between same-direction signals (default 30). Opposite-direction signals are not blocked.
School Toggles — Enable or disable each of the 7 Schools independently.
POC/EVWAP Smoothing — Raw or Hull smoothed. Hull length configurable.
Swing Period — Controls EVWAP re-anchoring sensitivity (default 55).
Volume Lookback — Bars analyzed for climax detection and volume statistics.
NB Min Samples — Minimum resolved outcomes before the Naive Bayes School starts voting.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, and it does not constitute a recommendation to buy, sell, or hold any financial instrument.
All trading involves risk. Past performance of any signal, voting system, or analytical method does not guarantee future results. The council votes, hit rates, and accuracy statistics displayed represent computational assessments based on the indicator's rules applied to historical data loaded in PulseWire. They are not predictions and should not be treated as certainties.
The Naive Bayes School learns from the chart data currently loaded. Its learned patterns may not generalize to future market conditions, different instruments, or different timeframes. The hit rates displayed in the dashboard reflect performance on the loaded chart history only and are subject to survivorship bias, lookback bias, and data limitations inherent to backtesting on historical bars.
No indicator, algorithm, or model — regardless of how many independent methods it combines — can account for all market variables including liquidity events, news-driven gaps, exchange outages, dark pool activity, or sudden regime changes.
Traders should always use independent risk management, position sizing, and their own judgment before entering any trade.
By using this indicator, you acknowledge that you are solely responsible for your own trading decisions and that the authors accept no liability for any losses incurred.
Indicator

Adaptive Linear Regression Structure [MarkitTick]💡 This indicator, is a sophisticated analytical tool designed to bridge the gap between classical statistical modeling and modern price action theory. By leveraging high-performance Ordinary Least Squares (OLS) calculations, it dynamically identifies the most statistically significant market structures—specifically linear regression channels—based on historical pivot points. Unlike static channels that rely on arbitrary lookback periods, this script scans a historical "horizon" of structural pivots to find the model with the highest mathematical "fit," providing traders with a non-repainting, objective view of trend exhaustion and volatility boundaries.
✨ Originality and Utility
● Dynamic Model Selection
Most linear regression indicators require the user to manually define a start and end point, or they use a fixed lookback period. This script is original because it treats the starting point of the regression as a variable. It scans multiple historical pivots (Highs and Lows) and performs a competitive analysis between different potential channels. The channel that is eventually displayed is the one that achieves the highest performance score, calculated via a combination of the Coefficient of Determination ($R^2$) and the natural log of the duration. This ensures the channel is both mathematically reliable and structurally relevant.
● Market Structure Integration
The utility of the indicator is enhanced by its "Market Structure Registry." Instead of calculating regressions on every single bar blindly, the script identifies "Pivot Highs" and "Pivot Lows" to use as anchors. This aligns the statistical modeling with the way professional traders view the market, focusing on major turning points rather than noise.
● Institutional-Grade Telemetry
The inclusion of a real-time HUD (Heads-Up Display) dashboard provides traders with immediate transparency into the model's health. By displaying the $R^2$ value and Z-Score, the indicator moves beyond simple "lines on a chart" and offers a quantitative assessment of how well the current price action respects the established trend.
🔬 Methodology and Concepts
● The OLS Kernel
At the heart of the script is a custom-built OLS (Ordinary Least Squares) method. It calculates the slope ($\beta$) and the intercept ($\alpha$) of the best-fit line through the closing prices of the selected period. The mathematical goal is to minimize the sum of the squared errors ( LSE:SSE $), ensuring the median line represents the "true" equilibrium of price over that duration.
● Heuristic Performance Scoring
The indicator does not just look for the highest correlation. It uses a "Performance Score" heuristic:
Score = $R^2$ * ln(Duration)
This formula rewards models that maintain a high degree of linearity over longer periods. A short-term channel with a high $R^2$ might be dismissed in favor of a long-term channel that has a slightly lower $R^2$ but significantly more structural weight.
● Volatility-Adjusted Envelopes
The upper and lower boundaries are not arbitrary. They are calculated based on the standard deviation of the residuals (the distance between actual price and the regression line). By applying a user-defined "Deviation Factor," the script creates volatility bands that expand or contract based on how "noisy" the trend is.
🎨 Visual Guide
● The Regression Channel
• Median Vector: A solid line representing the linear mean of the current trend. It is colored Cyan for bullish slopes and Orange for bearish slopes.
• Volatility Bands: Two solid lines flanking the median. These represent the "Deviation Factor" boundaries (defaulting to 2.0 standard deviations).
• Fill Core: A transparent background fill between the upper and lower bands, allowing for easy visualization of the "fair value" zone. The color dynamically shifts between Cyan and Orange based on the trend bias.
● Signal Labels
• LONG Labels: Cyan labels appearing below price when a "Mean Reversion" setup is detected (price crossing above the lower band).
• SHORT Labels: Orange labels appearing above price when a "Mean Reversion" setup is detected (price crossing below the upper band).
• Details: Labels include the Entry Price (EP), Take Profit (TP) at the median, and a suggested Stop Loss (SL).
● Telemetry Dashboard (HUD)
• Model Quality (R²): A value between 0.0 and 1.0. Values above 0.7 indicate a very strong trend.
• Trend Bias: Explicitly states "BULLISH" or "BEARISH."
• Deviation (Z-Score): Measures how many standard deviations the current price is away from the mean.
• Duration: Displays how many bars the current model covers.
📖 How to Use
● Mean Reversion Strategy
The primary use case is identifying overextended price action. When price moves outside the volatility bands (high Z-Score) and then crosses back inside, it suggests a return to the median "equilibrium" price.
• Bullish Entry: Look for a Cyan "LONG" label when price recovers from the lower band.
• Bearish Entry: Look for an Orange "SHORT" label when price pulls back from the upper band.
● Trend Strength Assessment
Use the $R^2$ value in the dashboard to filter trades. If the $R^2$ is low (e.g., below 0.5), the market is in a "Random Walk" phase, and the regression lines may be less reliable. High $R^2$ values suggest a "Trending" phase where the channel boundaries act as significant support and resistance.
● Dynamic Take Profits
The median line (the Cyan/Orange vector) serves as a dynamic take-profit target. Since the line is based on a linear slope, the price target adjusts every bar to reflect the ongoing trend.
⚙️ Inputs and Settings
● Algorithmic Core
• Scan Horizon: Determines how many historical pivots the script should evaluate. A higher number increases the "search depth" but requires more processing.
• Deviation Factor: Controls the width of the channel. A value of 2.0 covers approximately 95% of price action if the distribution is normal.
• Structural Sensitivity: Controls the lookback for the Pivot High/Low detection. Smaller values find more "local" structures; higher values find "major" structures.
● Signal Processing
• Quality Threshold (R²): This is a "gatekeeper" setting. If no model reaches this minimum quality, the indicator will not display a channel, protecting the user from weak or chaotic patterns.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Statistical Basis (OLS)
The indicator is grounded in the Gauss-Markov theorem. By calculating the slope via the covariance of time and price divided by the variance of time, it provides the "Best Linear Unbiased Estimator" (BLUE) of the current price trajectory.
● Information Theory & Heuristics
The scoring mechanism (using the natural log of N) draws inspiration from Information Criteria (like AIC or BIC). In statistical modeling, increasing the sample size ($N$) usually improves the model's reliability but can introduce "lag." By using the log of duration, the script balances the benefit of a larger sample size against the need for current relevance.
● Standardized Residuals (Z-Scores)
The "Z-Metric" displayed in the dashboard is a calculation of:
$Z = (Price - Estimated Price) / Standard Error$
This standardizes the distance of price from the mean across different assets and timeframes, allowing for a universal interpretation of "overbought" or "oversold" conditions based on the specific volatility of the current trend.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. Indicator

DCA Investment Tracker Pro [tradeviZion]DCA Investment Tracker Pro: Educational DCA Analysis Tool
An educational indicator that helps analyze Dollar-Cost Averaging strategies by comparing actual performance with historical data calculations.
---
💡 Why I Created This Indicator
As someone who practices Dollar-Cost Averaging, I was frustrated with constantly switching between spreadsheets, calculators, and charts just to understand how my investments were really performing. I wanted to see everything in one place - my actual performance, what I should expect based on historical data, and most importantly, visualize where my strategy could take me over the long term .
What really motivated me was watching friends and family underestimate the incredible power of consistent investing. When Napoleon Bonaparte first learned about compound interest, he reportedly exclaimed "I wonder it has not swallowed the world" - and he was right! Yet most people can't visualize how their $500 monthly contributions today could become substantial wealth decades later.
Traditional DCA tracking tools exist, but they share similar limitations:
Require manual data entry and complex spreadsheets
Use fixed assumptions that don't reflect real market behavior
Can't show future projections overlaid on actual price charts
Lose the visual context of what's happening in the market
Make compound growth feel abstract rather than tangible
I wanted to create something different - a tool that automatically analyzes real market history, detects volatility periods, and shows you both current performance AND educational projections based on historical patterns right on your PulseWire charts. As Warren Buffett said: "Someone's sitting in the shade today because someone planted a tree a long time ago." This tool helps you visualize your financial tree growing over time.
This isn't just another calculator - it's a visualization tool that makes the magic of compound growth impossible to ignore.
---
🎯 What This Indicator Does
This educational indicator provides DCA analysis tools. Users can input investment scenarios to study:
Theoretical Performance: Educational calculations based on historical return data
Comparative Analysis: Study differences between actual and theoretical scenarios
Historical Projections: Theoretical projections for educational analysis (not predictions)
Performance Metrics: CAGR, ROI, and other analytical metrics for study
Historical Analysis: Calculates historical return data for reference purposes
---
🚀 Key Features
Volatility-Adjusted Historical Return Calculation
Analyzes 3-20 years of actual price data for any symbol
Automatically detects high-volatility stocks (meme stocks, growth stocks)
Uses median returns for volatile stocks, standard CAGR for stable stocks
Provides conservative estimates when extreme outlier years are detected
Smart fallback to manual percentages when data insufficient
Customizable Performance Dashboard
Educational DCA performance analysis with compound growth calculations
Customizable table sizing (Tiny to Huge text options)
9 positioning options (Top/Middle/Bottom + Left/Center/Right)
Theme-adaptive colors (automatically adjusts to dark/light mode)
Multiple display layout options
Future Projection System
Visual future growth projections
Timeframe-aware calculations (Daily/Weekly/Monthly charts)
1-30 year projection options
Shows projected portfolio value and total investment amounts
Investment Insights
Performance vs benchmark comparison
ROI from initial investment tracking
Monthly average return analysis
Investment milestone alerts (25%, 50%, 100% gains)
Contribution tracking and next milestone indicators
---
📊 Step-by-Step Setup Guide
1. Investment Settings 💰
Initial Investment: Enter your starting lump sum (e.g., $60,000)
Monthly Contribution: Set your regular DCA amount (e.g., $500/month)
Return Calculation: Choose "Auto (Stock History)" for real data or "Manual" for fixed %
Historical Period: Select 3-20 years for auto calculations (default: 10 years)
Start Year: When you began investing (e.g., 2020)
Current Portfolio Value: Your actual portfolio worth today (e.g., $150,000)
2. Display Settings 📊
Table Sizes: Choose from Tiny, Small, Normal, Large, or Huge
Table Positions: 9 options - Top/Middle/Bottom + Left/Center/Right
Visibility Toggles: Show/hide Main Table and Stats Table independently
3. Future Projection 🔮
Enable Projections: Toggle on to see future growth visualization
Projection Years: Set 1-30 years ahead for analysis
Live Example - NASDAQ:META Analysis:
Settings shown: $60K initial + $500/month + Auto calculation + 10-year history + 2020 start + $150K current value
---
🔬 Pine Script Code Examples
Core DCA Calculations:
// Calculate total invested over time
months_elapsed = (year - start_year) * 12 + month - 1
total_invested = initial_investment + (monthly_contribution * months_elapsed)
// Compound growth formula for initial investment
theoretical_initial_growth = initial_investment * math.pow(1 + annual_return, years_elapsed)
// Future Value of Annuity for monthly contributions
monthly_rate = annual_return / 12
fv_contributions = monthly_contribution * ((math.pow(1 + monthly_rate, months_elapsed) - 1) / monthly_rate)
// Total expected value
theoretical_total = theoretical_initial_growth + fv_contributions
Volatility Detection Logic:
// Detect extreme years for volatility adjustment
extreme_years = 0
for i = 1 to historical_years
yearly_return = ((price_current / price_i_years_ago) - 1) * 100
if yearly_return > 100 or yearly_return < -50
extreme_years += 1
// Use median approach for high volatility stocks
high_volatility = (extreme_years / historical_years) > 0.2
calculated_return = high_volatility ? median_of_returns : standard_cagr
Performance Metrics:
// Calculate key performance indicators
absolute_gain = actual_value - total_invested
total_return_pct = (absolute_gain / total_invested) * 100
roi_initial = ((actual_value - initial_investment) / initial_investment) * 100
cagr = (math.pow(actual_value / initial_investment, 1 / years_elapsed) - 1) * 100
---
📊 Real-World Examples
See the indicator in action across different investment types:
Stable Index Investments:
AMEX:SPY (SPDR S&P 500) - Shows steady compound growth with standard CAGR calculations
Classic DCA success story: $60K initial + $500/month starting 2020. The indicator shows SPY's historical 10%+ returns, demonstrating how consistent broad market investing builds wealth over time. Notice the smooth theoretical growth line vs actual performance tracking.
MIL:VUAA (Vanguard S&P 500 UCITS) - Shows both data limitation and solution approaches
Data limitation example: VUAA shows "Manual (Auto Failed)" and "No Data" when default 10-year historical setting exceeds available data. The indicator gracefully falls back to manual percentage input while maintaining all DCA calculations and projections.
MIL:VUAA (Vanguard S&P 500 UCITS) - European ETF with successful 5-year auto calculation
Solution demonstration: By adjusting historical period to 5 years (matching available data), VUAA auto calculation works perfectly. Shows how users can optimize settings for newer assets. European market exposure with EUR denomination, demonstrating DCA effectiveness across different markets and currencies.
NYSE:BRK.B (Berkshire Hathaway) - Quality value investment with Warren Buffett's proven track record
Value investing approach: Berkshire Hathaway's legendary performance through DCA lens. The indicator demonstrates how quality companies compound wealth over decades. Lower volatility than tech stocks = standard CAGR calculations used.
High-Volatility Growth Stocks:
NASDAQ:NVDA (NVIDIA Corporation) - Demonstrates volatility-adjusted calculations for extreme price swings
High-volatility example: NVIDIA's explosive AI boom creates extreme years that trigger volatility detection. The indicator automatically switches to "Median (High Vol): 50%" calculations for conservative projections, protecting against unrealistic future estimates based on outlier performance periods.
NASDAQ:TSLA (Tesla) - Shows how 10-year analysis can stabilize volatile tech stocks
Stable long-term growth: Despite Tesla's reputation for volatility, the 10-year historical analysis (34.8% CAGR) shows consistent enough performance that volatility detection doesn't trigger. Demonstrates how longer timeframes can smooth out extreme periods for more reliable projections.
NASDAQ:META (Meta Platforms) - Shows stable tech stock analysis using standard CAGR calculations
Tech stock with stable growth: Despite being a tech stock and experiencing the 2022 crash, META's 10-year history shows consistent enough performance (23.98% CAGR) that volatility detection doesn't trigger. The indicator uses standard CAGR calculations, demonstrating how not all tech stocks require conservative median adjustments.
Notice how the indicator automatically detects high-volatility periods and switches to median-based calculations for more conservative projections, while stable investments use standard CAGR methods.
---
📈 Performance Metrics Explained
Current Portfolio Value: Your actual investment worth today
Expected Value: What you should have based on historical returns (Auto) or your target return (Manual)
Total Invested: Your actual money invested (initial + all monthly contributions)
Total Gains/Loss: Absolute dollar difference between current value and total invested
Total Return %: Percentage gain/loss on your total invested amount
ROI from Initial Investment: How your starting lump sum has performed
CAGR: Compound Annual Growth Rate of your initial investment (Note: This shows initial investment performance, not full DCA strategy)
vs Benchmark: How you're performing compared to the expected returns
---
⚠️ Important Notes & Limitations
Data Requirements: Auto mode requires sufficient historical data (minimum 3 years recommended)
CAGR Limitation: CAGR calculation is based on initial investment growth only, not the complete DCA strategy
Projection Accuracy: Future projections are theoretical and based on historical returns - actual results may vary
Timeframe Support: Works ONLY on Daily (1D), Weekly (1W), and Monthly (1M) charts - no other timeframes supported
Update Frequency: Update "Current Portfolio Value" regularly for accurate tracking
---
📚 Educational Use & Disclaimer
This analysis tool can be applied to various stock and ETF charts for educational study of DCA mathematical concepts and historical performance patterns.
Study Examples: Can be used with symbols like AMEX:SPY , NASDAQ:QQQ , AMEX:VTI , NASDAQ:AAPL , NASDAQ:MSFT , NASDAQ:GOOGL , NASDAQ:AMZN , NASDAQ:TSLA , NASDAQ:NVDA for learning purposes.
EDUCATIONAL DISCLAIMER: This indicator is a study tool for analyzing Dollar-Cost Averaging strategies. It does not provide investment advice, trading signals, or guarantees. All calculations are theoretical examples for educational purposes only. Past performance does not predict future results. Users should conduct their own research and consult qualified financial professionals before making any investment decisions.
---
© 2025 TradeVizion. All rights reserved.
Indicator

Indicator

Smart Money Index + True Strength IndexThe Smart Money Index + True Strength Index indicator is a combination of two popular technical analysis indicators: the Smart Money Index (SMI) and the True Strength Index (TSI). This combined indicator helps traders identify potential entry points for long and short positions based on signals from both indexes.
Main Components:
Smart Money Index (SMI):
The SMI measures the difference between the closing and opening price of a candle multiplied by the trading volume over a certain period of time. This allows you to assess the activity of large players ("smart money") in the market. If the SMI value is above a certain threshold (smiThreshold), it may indicate a bullish trend, and if lower, it may indicate a bearish trend.
True Strength Index (TSI):
The TSI is an oscillator that measures the strength of a trend by comparing the price change of the current bar with the previous bar. It uses two exponential moving averages (EMAS) to smooth the data. TSI values can fluctuate around zero, with values above the overbought level indicating a possible downward correction, and values below the oversold level signaling a possible upward correction.
Parameters:
SMI Length: Defines the number of candles used to calculate the average SMI value. The default value is 14.
SMI Threshold: A threshold value that is used to determine a buy or sell signal. The default value is 0.
Length of the first TSI smoothing (tsiLength1): The length of the first EMA for calculating TSI. The default value is 25.
Second TSI smoothing length (tsiLength2): The length of the second EMA for additional smoothing of TSI values. The default value is 13.
TSI Overbought level: The level at which the market is considered to be overbought. The default value is 25.
Oversold level TSI: The level at which it is considered that the market is in an oversold state. The default value is -25.
Logic of operation:
SMI calculation:
First, the difference between the closing and opening price of each candle (close - open) is calculated.
This difference is then multiplied by the trading volume.
The resulting product is averaged using a simple moving average (SMA) over a specified period (smiLength).
Calculation of TSI:
The price change relative to the previous bar is calculated (close - close ).
The first EMA with the length tsiLength1 is applied.
Next, a second EMA with a length of tsiLength2 is applied to obtain the final TSI value.
The absolute value of price changes is calculated in the same way, and two emas are also applied.
The final TSI index is calculated as the ratio of these two values multiplied by 100.
Graphical representation:
The SMI and TSI lines are plotted on the graph along with their respective thresholds.
For SMI, the line is drawn in orange, and the threshold level is dotted in gray.
For the TSI, the line is plotted in blue, the overbought and oversold levels are indicated by red and green dotted lines, respectively.
Conditions for buy/sell signals:
A buy (long) signal is generated when:
SMI is greater than the threshold (smi > smiThreshold)
TSI crosses the oversold level from bottom to top (ta.crossover(tsi, oversold)).
A sell (short) signal is generated when:
SMI is less than the threshold (smi < smiThreshold)
TSI crosses the overbought level from top to bottom (ta.crossunder(tsi, overbought)).
Signal display:
When the conditions for a long or short are met, labels labeled "LONG" or "SHORT" appear on the chart.
The label for the long is located under the candle and is colored green, and for the short it is above the candle and is colored red.
Notification generation:
The indicator also supports notifications via the PulseWire platform. Notifications are sent when conditions arise for a long or short position.
This combined indicator provides the trader with the opportunity to use both SMI and TSI signals simultaneously, which can improve the accuracy of trading decisions.
Indicator

analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics Library

Buy-Sell-Hold RecommendationsDescription:
The indicator displays "recommendations" for the active symbol (Buy, Strong buy, Sell, Strong sell or Hold), based on the Tradingview's recommendations data. There are 3 presentations you can choose from:
- Bar -> displays a vertical/horizontal bar with sections for each rating
- Pie chart -> displays a pie chart with sections
- Table -> displays a table with score for each recommendation
Inputs:
- Display mode -> data presentation mode
- Position -> position of the bar/pie chart/table
- Highlight the highest rating -> recommendation(s) with highest score will be highlighted
- Buy, Strong buy, Sell, etc. -> colors of the "bar" sections
- Pixel Width, Pixel Height, etc. -> size of each "pixel" (cell) of the pie chart
- Resolution (X), Resolution (Y) -> how many pixels (cells) the pie chart has on each axis
- Inner area size (%) -> size of the empty space at the center of the pie chart
- Invert theme -> invert coloring scheme for "table" presentation mode
Notes:
- Tradingview seems to provide the recommendations only for major stocks
- Data is taken directly from Tradingview and is based on opinions of "analysts" Indicator
