OPEN-SOURCE SCRIPT
Multi-MA Trend Ribbon [MarkitTick]

💡 A fully adaptive moving-average ribbon that lets you choose from 30 different smoothing algorithms — from classic SMA/EMA to advanced adaptive filters like Kalman, JMA, KAMA, and a custom volatility-responsive method called LLAMA — then builds a multi-line, gradient-colored trend ribbon out of that single chosen method across up to 8 progressively longer lengths. Layered on top is an optional multi-timeframe bias filter, an ADX strength gate, a volume confirmation gate, webhook-ready JSON alerts, and a live diagnostic dashboard.
✨ Originality and Utility
Most ribbon-style indicators on the platform hard-code a single averaging method (usually EMA or HMA) and stack a handful of fixed lengths on the chart. This script takes a different approach: it treats the "ribbon" as a generic container and the "moving average type" as a fully interchangeable engine, with 30 distinct algorithms available from a single dropdown, all built from first principles (not by calling a bundle of pre-packaged libraries). Because every ribbon line is generated by the same underlying function at different lengths, switching the MA Type instantly re-renders the entire ribbon in the new smoothing style, giving traders a single tool to compare how trend-following behaves under drastically different mathematical assumptions (linear vs. exponential weighting, adaptive vs. fixed responsiveness, zero-lag vs. standard lag) without switching indicators.
The script's originality centers on three custom-built components not found in standard built-ins:
The mashup of a trend ribbon, a confluence filter stack (ADX + HTF + Volume), and a webhook alert system is justified because these three layers solve three different practical problems traders face together: identifying trend direction (ribbon), avoiding low-quality signals in choppy or thin conditions (filters), and automating execution (alerts) — components that are commonly used in sequence by discretionary and systematic traders alike, making their integration into one tool a genuine workflow simplification rather than an arbitrary bundling.
🔬 Methodology and Concepts
● Core Ribbon Construction
The script computes eight moving averages of the same source (default: close) at lengths that increase by a fixed step from a base length. For example, with a Base of 20 and a Step of 10, the eight lengths used are 20, 30, 40, 50, 60, 70, 80, and 90. The fastest line (MA1) and the slowest visible line (determined by the Lines setting) are compared: when the fast line sits above the slow line, the ribbon is considered to be in a bullish regime; when below, bearish. All eight lines are generated by the exact same averaging function, so the "shape" of the ribbon (how tightly or loosely the lines fan out) becomes a visual proxy for trend strength and consistency across time horizons.
● Selectable Smoothing Engine
The Type input lets you choose the mathematical method used to compute every single line in the ribbon simultaneously. The available families are:
• LLAMA and the Directional Predictor
LLAMA (the script's custom adaptive method) works in two stages. First, a directional forecast is built from two RSI readings (14-period and 28-period). Over a lookback window, each prior bar is scored by how closely its RSI signature matches the current bar's RSI signature (using a log-distance similarity weighting), and that similarity is used to weight whether price rose or fell on that historical bar. The weighted average of those historical outcomes produces a forecast value between -1 (strongly bearish precedent) and +1 (strongly bullish precedent). Second, that forecast value is used to stretch or compress each ribbon line's effective length within a configurable percentage range around its base length — a stronger bullish or bearish forecast pushes the effective length toward one end of the range, changing how reactive that specific line is to new price action. This effective length is then converted into a standard exponential smoothing constant to produce the final LLAMA value. The result is a moving average that behaves less like a fixed-parameter tool and more like a filter that continuously recalibrates its own sensitivity based on recent directional evidence.
● Trend Signals
Two categories of signals are generated:
● Confluence Filters
Three optional, independently toggleable filters can be layered onto both signal types to suppress low-quality triggers:
🎨 Visual Guide
📖 How to Use
⚙️ Inputs and Settings
⚠️ Confirmation Lag Notice
The Shift input allows ribbon lines to be plotted with a backward or forward bar offset relative to the current price bar. When a non-zero Shift value is used, what you see plotted at a given bar's x-position does not represent that bar's actual calculated value in real time — always verify the Shift setting is at its default (0) if you intend to use the ribbon for real-time signal interpretation, and be aware that a non-zero offset can visually misrepresent how early or late a line's response to price actually was.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
This script draws on several distinct threads of technical and quantitative theory:
⚠️ 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. We 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.
✨ Originality and Utility
Most ribbon-style indicators on the platform hard-code a single averaging method (usually EMA or HMA) and stack a handful of fixed lengths on the chart. This script takes a different approach: it treats the "ribbon" as a generic container and the "moving average type" as a fully interchangeable engine, with 30 distinct algorithms available from a single dropdown, all built from first principles (not by calling a bundle of pre-packaged libraries). Because every ribbon line is generated by the same underlying function at different lengths, switching the MA Type instantly re-renders the entire ribbon in the new smoothing style, giving traders a single tool to compare how trend-following behaves under drastically different mathematical assumptions (linear vs. exponential weighting, adaptive vs. fixed responsiveness, zero-lag vs. standard lag) without switching indicators.
The script's originality centers on three custom-built components not found in standard built-ins:
- A proprietary adaptive length mechanism ("LLAMA") that dynamically expands or contracts each ribbon line's effective lookback based on a short-term directional forecast, rather than using a static length.
- A dual-RSI-divergence-weighted directional predictor that feeds that adaptive length engine.
- A from-scratch implementation of less commonly available filters (Kalman, JMA, FRAMA, T3, McGinley, Super Smoother) that are not native Pine built-ins, giving traders access to algorithms usually reserved for institutional charting platforms or custom research code.
The mashup of a trend ribbon, a confluence filter stack (ADX + HTF + Volume), and a webhook alert system is justified because these three layers solve three different practical problems traders face together: identifying trend direction (ribbon), avoiding low-quality signals in choppy or thin conditions (filters), and automating execution (alerts) — components that are commonly used in sequence by discretionary and systematic traders alike, making their integration into one tool a genuine workflow simplification rather than an arbitrary bundling.
🔬 Methodology and Concepts
● Core Ribbon Construction
The script computes eight moving averages of the same source (default: close) at lengths that increase by a fixed step from a base length. For example, with a Base of 20 and a Step of 10, the eight lengths used are 20, 30, 40, 50, 60, 70, 80, and 90. The fastest line (MA1) and the slowest visible line (determined by the Lines setting) are compared: when the fast line sits above the slow line, the ribbon is considered to be in a bullish regime; when below, bearish. All eight lines are generated by the exact same averaging function, so the "shape" of the ribbon (how tightly or loosely the lines fan out) becomes a visual proxy for trend strength and consistency across time horizons.
● Selectable Smoothing Engine
The Type input lets you choose the mathematical method used to compute every single line in the ribbon simultaneously. The available families are:
- Classic weighted averages: SMA, EMA, RMA (Wilder's smoothing), WMA, Triangular (TRIMA), Volume-Weighted (VWMA), and their double/triple-smoothed variants (DWMA/TWMA, DVWMA/TVWMA) which apply the same weighting function recursively to reduce lag-vs-noise trade-offs.
- Zero/reduced-lag filters: Hull MA (HMA) and its extended variants EHMA and THMA, DEMA and TEMA (double/triple exponential smoothing, per Patrick Mulloy's original error-correction concept), and ZLEMA (zero-lag EMA using a momentum-shifted input).
- Adaptive/volatility-responsive filters: KAMA (Kaufman's Adaptive MA, which speeds up or slows down based on an efficiency ratio of net movement to total movement), VIDYA (Chande's Variable Index Dynamic Average, which scales its responsiveness using Chande Momentum Oscillator readings), FRAMA (Ehlers' Fractal Adaptive MA, which estimates a fractal dimension from recent high/low ranges to adjust smoothing), and JMA (a Jurik-style adaptive filter using a two-stage predictive/corrective recursive structure).
- Specialized/legacy filters: T3 (Tillson's six-pole exponential blend using a volume factor to control overshoot), McGinley Dynamic (a self-adjusting average that speeds up during fast markets and slows down during consolidation via a ratio-based denominator), ALMA (Arnaud Legoux MA, a Gaussian-weighted average with adjustable offset and smoothness), LSMA (least-squares linear regression endpoint), SWMA (a fixed symmetric 4-bar weighted average), Median, and SSF (a two-pole Super Smoother Filter using an Ehlers-style recursive IIR design).
- Proprietary adaptive engine — LLAMA: A custom exponential filter whose smoothing constant is derived not from a fixed length, but from a dynamically computed effective length (see below).
• LLAMA and the Directional Predictor
LLAMA (the script's custom adaptive method) works in two stages. First, a directional forecast is built from two RSI readings (14-period and 28-period). Over a lookback window, each prior bar is scored by how closely its RSI signature matches the current bar's RSI signature (using a log-distance similarity weighting), and that similarity is used to weight whether price rose or fell on that historical bar. The weighted average of those historical outcomes produces a forecast value between -1 (strongly bearish precedent) and +1 (strongly bullish precedent). Second, that forecast value is used to stretch or compress each ribbon line's effective length within a configurable percentage range around its base length — a stronger bullish or bearish forecast pushes the effective length toward one end of the range, changing how reactive that specific line is to new price action. This effective length is then converted into a standard exponential smoothing constant to produce the final LLAMA value. The result is a moving average that behaves less like a fixed-parameter tool and more like a filter that continuously recalibrates its own sensitivity based on recent directional evidence.
● Trend Signals
Two categories of signals are generated:
- Ribbon Flips: Triggered when the relationship between the fastest line and the slowest visible line changes state (fast crosses from below to above the slow line, or vice versa), using confirmed prior-bar values to avoid intrabar flicker.
- Price Crosses: Triggered when price itself crosses the fastest ribbon line (MA1), independent of the broader ribbon state, offering an earlier but noisier entry cue.
● Confluence Filters
Three optional, independently toggleable filters can be layered onto both signal types to suppress low-quality triggers:
- ADX Strength Filter: Requires Wilder's Average Directional Index (calculated via the standard DMI/ADX formula) to be above a minimum threshold before a signal is allowed to fire, filtering out signals generated during weak or range-bound conditions.
- Higher-Timeframe Bias Filter: Recomputes the entire ribbon logic (fast MA vs. slow MA) on a user-selected higher timeframe and requires the current-timeframe signal to agree with that higher-timeframe bias before firing. This uses a confirmed prior-bar value pulled via request.security() with lookahead explicitly enabled on historical (already-closed) data only, so no future information leaks into the calculation.
- Volume Confirmation Filter: Requires the prior bar's volume to exceed a multiple of its recent average volume, ensuring signals are backed by above-average participation rather than occurring on thin, low-conviction bars.
🎨 Visual Guide
- Ribbon Lines (MA1–MA8): Up to eight plotted lines, one per configured length, colored on a gradient. When Trend Col is enabled, the gradient runs between your chosen Bull and Bear colors depending on the current trend state; when disabled, it instead runs between the Fast and Slow colors you've set, regardless of trend direction.
- Ribbon Fill: The semi-transparent shaded area between each consecutive pair of ribbon lines, colored to match the current trend (bull or bear color) with adjustable transparency via the Fill Transparency setting. A tightly compressed, thin fill indicates the ribbon lines are converging (potential consolidation or transition); a wide, expanded fill indicates strong trend separation.
- Bull/Bear Flip Markers: Small triangle shapes below or above the bars marking the exact bar where a confirmed Ribbon Flip occurred — an upward triangle in your Bull color for bullish flips, a downward triangle in your Bear color for bearish flips.
- Heatmap Candles (optional): When enabled, replaces standard candle coloring with your chosen Bull/Bear body and border colors based on the ribbon's current trend state, turning the entire chart into an at-a-glance trend heatmap.
- Dashboard Table: An on-chart panel (position configurable) summarizing, in real time: signal lock status, current bias, active MA type and lengths, a visual bar-graph readout of the number of active ribbon lines, the fast and slow MA values, the current spread between them, the LLAMA directional prediction strength, the most recent flip direction, the most recent price cross direction, how many filters are currently active, the live ADX reading, the +DI/-DI values, the current volume ratio versus average, and the higher-timeframe bias state.
📖 How to Use
- Use the overall ribbon color and fill (bull color vs. bear color) as your primary trend read: a consistently bull-colored, moderately expanded ribbon suggests sustained upward momentum, while contraction or color-flipping suggests indecision.
- Treat triangle Flip markers as your core trend-change signal — they only appear once the flip has been confirmed on a closed bar, and (if filters are enabled) only after passing your chosen strength, HTF-agreement, and volume conditions.
- Treat Price Cross events (visible in the dashboard's "Price Cross" row) as a faster, more aggressive alternative entry cue for traders who want to react before a full ribbon flip occurs, understanding this comes with a higher likelihood of false signals.
- Enable the Lock Signal option to freeze the current bias and temporarily suspend new signal generation — useful when you want to hold a view steady while manually reviewing a setup instead of reacting to every subsequent flip.
- Watch the dashboard's Filters and individual ADX / Vol Ratio / HTF Bias rows to understand in real time why a signal is or is not being permitted to fire.
- Consider combining a slower Type (e.g., RMA, T3, or a longer-length adaptive filter) for the overall bias with faster Price Cross signals for tactical entries within that bias.
⚙️ Inputs and Settings
- Type: Selects which of the 30 supported averaging methods is used to build every line in the ribbon.
- Src: The price source fed into all calculations (default: close).
- Base / Step: Base sets the length of the fastest ribbon line; Step sets the length increment applied to each subsequent line. Together they define the full spread of lengths across the ribbon.
- Shift: Applies a horizontal bar offset to all plotted ribbon lines. A non-zero value shifts the visual plot forward or backward relative to price and does not alter the underlying calculation.
- Lines: Sets how many of the eight possible ribbon lines are displayed (2–8), which also determines which line is treated as the "slow" reference line for bias and flip calculations.
- ALMA Off / ALMA Sig, T3 Vf, KAMA Fast / KAMA Slow, JMA Phase / JMA Pow, Kal Q / Kal R, LLAMA LB / LLAMA Rng: Method-specific tuning parameters that only take effect when the corresponding Type is selected — these control offset/smoothness for ALMA, volume factor for T3, the fast/slow efficiency bounds for KAMA, phase/power for JMA, process/measurement noise for Kalman, and lookback/range for the custom LLAMA engine.
- ADX / HTF / Vol toggles and their sub-settings: Independently enable and configure the three confluence filters described in the Methodology section (strength threshold and length for ADX, target timeframe for HTF, lookback length and multiplier for Volume).
- Lock Signal: Freezes the currently displayed bias and suppresses new flip/cross signals until disabled.
- Trend Col / Fill / Fill Transparency / Width / Bars / Signals: Visual controls for whether ribbon coloring reflects trend state, whether the fill between lines is shown and how transparent it is, line thickness, whether heatmap candles are shown, and whether flip markers are plotted.
- Dashboard Show / Position: Toggles the on-chart dashboard and sets its screen position.
- Alert toggles and Action fields: Enable/disable Flip-based and Cross-based alerts independently, and customize the text string sent in each alert's JSON payload for long entry, short entry, close-long, close-short, cross-up, and cross-down events — designed to be dropped directly into webhook-based automation.
⚠️ Confirmation Lag Notice
The Shift input allows ribbon lines to be plotted with a backward or forward bar offset relative to the current price bar. When a non-zero Shift value is used, what you see plotted at a given bar's x-position does not represent that bar's actual calculated value in real time — always verify the Shift setting is at its default (0) if you intend to use the ribbon for real-time signal interpretation, and be aware that a non-zero offset can visually misrepresent how early or late a line's response to price actually was.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
This script draws on several distinct threads of technical and quantitative theory:
- Classical trend-following theory: The core "fast MA vs. slow MA" bias mechanism traces back to Dow Theory's premise that trend direction can be inferred by comparing price behavior across different time horizons — approximated here by comparing smoothed averages of different lengths rather than raw price.
- Exponential smoothing and digital filter theory: Methods like EMA, DEMA, TEMA, and ZLEMA build on Patrick Mulloy's work on reducing the inherent lag of exponential moving averages through cascaded and momentum-adjusted smoothing, itself grounded in classical infinite impulse response (IIR) filter design from signal processing.
- Adaptive filter theory: KAMA (Kaufman), VIDYA (Chande), and FRAMA (Ehlers) all apply the same broader principle from adaptive control theory — that a filter's time constant should not be fixed but should respond to a real-time measurement of market "efficiency" or "noise," whether measured via a directional efficiency ratio, momentum oscillator magnitude, or fractal dimension of price geometry.
- State-space estimation theory: The Kalman filter option applies the classical Kalman filtering framework from control and estimation theory — treating the true underlying trend as a hidden state to be recursively estimated from noisy price observations, balancing a process-noise parameter (how much the true state is expected to drift) against a measurement-noise parameter (how much to trust each new observation).
- Fractal market theory: FRAMA's dimension calculation is grounded in Mandelbrot's fractal geometry concepts as adapted by John Ehlers, using the scaling relationship between price range measured at different resolutions to infer whether the market is behaving more like a trending (lower fractal dimension) or random-walk (higher fractal dimension) process.
- Directional Movement / trend strength theory: The ADX filter implements Welles Wilder's original Directional Movement System, which decomposes price movement into positive and negative directional components and derives a smoothed strength index from their divergence.
- Weighted similarity / kernel-based forecasting: The custom LLAMA predictor's weighting scheme is conceptually related to kernel-weighted (locally weighted) regression and nearest-neighbor forecasting methods, in which historical observations are weighted by their similarity to current conditions (here, measured via RSI-signature distance) rather than treated with uniform recency weighting.
⚠️ 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. We 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.
Mã nguồn mở
Theo đúng tinh thần TradingView, tác giả của tập lệnh này đã công bố nó dưới dạng mã nguồn mở, để các nhà giao dịch có thể xem xét và xác minh chức năng. Chúc mừng tác giả! Mặc dù bạn có thể sử dụng miễn phí, hãy nhớ rằng việc công bố lại mã phải tuân theo Nội quy.
💡 Proprietary indicators. Original research. Built by analysts who trade.
👑 Premium: markittick.com
📢 Free Telegram: t.me/MarkitTick_Updates
👑 Premium: markittick.com
📢 Free Telegram: t.me/MarkitTick_Updates
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.
Mã nguồn mở
Theo đúng tinh thần TradingView, tác giả của tập lệnh này đã công bố nó dưới dạng mã nguồn mở, để các nhà giao dịch có thể xem xét và xác minh chức năng. Chúc mừng tác giả! Mặc dù bạn có thể sử dụng miễn phí, hãy nhớ rằng việc công bố lại mã phải tuân theo Nội quy.
💡 Proprietary indicators. Original research. Built by analysts who trade.
👑 Premium: markittick.com
📢 Free Telegram: t.me/MarkitTick_Updates
👑 Premium: markittick.com
📢 Free Telegram: t.me/MarkitTick_Updates
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.