Isolated Scroll Container

1. Auto-Length Moving Average + Trend Signals Strategy Description

A moving average whose own length stretches or snaps back bar by bar, driven by whichever market condition you pick (slope, RSI, volume, Bollinger, MACD, Stochastic, CCI, momentum, or none at all). On top of that adaptive line sits a second, smoother line used only to judge direction and to colour circles, triangles and a 0–100 "trend score" shown in two on-chart tables.

1.1 Indicator Concept

A fixed-length moving average is always a trade-off: short = fast but whipsaws in a range, long = smooth but late into a trend. This indicator's answer is a moving average that changes its own length while you watch: it starts short (fast) and grows longer (smoother) for every bar that a chosen condition keeps agreeing with the direction it already had, then snaps back to short the instant that condition disagrees or goes neutral.

  • A counter drives the length. A counter starts at 1 and the moving-average length is always Base MA Length + (counter − 1), capped at Max Dynamic Length. As long as the chosen condition keeps pointing the same way bar after bar, the counter keeps climbing and the average gets longer and smoother. The moment the condition flips direction or goes neutral, the counter drops back to 1 and the average snaps back to its base (fast) length.
  • Nine ways to decide "does it still agree". You choose one: the slope of the average itself, an RSI zone, volume versus its own average, a Bollinger Band break, a MACD cross, a Stochastic zone, a CCI zone, the sign of momentum (rate of change), or None — which disables the whole mechanism and leaves a plain fixed-length average.
  • The counter can grow forever, or rock back and forth. By default it keeps climbing (capped only by Max Dynamic Length). An optional "Reverse Counter" mode makes it climb to a ceiling (Counter Break) and then count back down to 1 and climb again — a repeating sawtooth — so the average never gets stuck at its longest, smoothest setting forever.
  • A second, invisible line does the trend judging. The adaptive average is fed into a two-pole smoothing filter that produces a slower "filtered trend" line. This filtered line — not the plotted average — is what the indicator watches to decide whether the market is rising or falling, for how many bars in a row, and to colour the circles, triangles and the average line itself.
  • A 0–100 score tracks how far the counter has travelled. Every bar the counter's progress toward Counter Break is turned into a percentage; the indicator also remembers the highest score and the running average score since the chart was loaded.

In short: an adaptive moving average that automatically widens in sustained, one-directional conditions and narrows back the instant that condition breaks — plus a slower trend layer, confirmation markers and two information tables built on top of it.

1.2 Indicator Features

  • Display:
    • The dynamic MA line (2px wide), coloured lime once a confirmed up-run has lasted long enough, red once a confirmed down-run has, otherwise yellow (50% transparent by default).
    • A soft fill between the MA line and an invisible EMA(10) of price, tinted lime while price is above the MA (since the last cross) or red while it is below, 70% transparent.
    • Circles placed an ATR(200) above or below the (invisible) filtered-trend line once a trend has been confirmed for long enough — colour follows a yellow-to-lime / yellow-to-red gradient that deepens the longer the run has lasted.
    • Triangles marking the exact bar a confirmed trend state begins, plus two faint duplicate shapes underneath each one (different size/transparency) for a soft halo effect.
    • Trend Strength table (top-right, optional): Reset Condition, Counter Value, Trend Strength (0–100), Highest Trend Score, Average Trend Score.
    • Reset Mode Guidance table (bottom-right, optional): a single row describing the currently selected Reset Condition — who it suits and its key benefit.
  • Alerts: The indicator has NO alertcondition() calls. Anything event-based must be added by hand.

1.3 How to Use the Indicator

  • Read the MA's length behaviour as a regime gauge. A line that keeps hugging price closely and resetting often means the chosen condition keeps flipping — typically a choppy or ranging stretch. A line that visibly smooths out and lags more means the condition has agreed with one direction for a long run — typically a sustained trend.
  • Pick the Reset Condition to match your read of the market. Slope suits trend followers; RSI/Stochastic/CCI suit traders watching for overbought/oversold extremes; Volume suits breakout traders looking for above-average participation; Bollinger suits volatility traders; MACD/Momentum suit traders tracking acceleration; None turns the indicator into a plain fixed-length SMA, useful as a baseline comparison.
  • Turn on "Reverse Counter After Break" if you do not want the average parked at its longest, smoothest setting for an entire extended trend — it will cycle the length back down and up again instead. Leave it off for maximum smoothing during long, steady runs.
  • Treat the MA's colour and the circles/triangles as two separately-tuned confirmation layers, not one. The line colour reacts to its own bar-count threshold ("Trend Confirmation Length") and the circles/triangles to a different one ("Trending Periods") — they can disagree about whether a trend is "confirmed" yet. Check both settings if the two ever seem out of sync.
  • Use the Trend Strength number as "how far the counter has progressed toward Counter Break", not as a measure of how strong the move is in price terms. 0 means the counter just reset; 100 means it just reached (or passed) Counter Break.
  • Remember Highest/Average Trend Score are lifetime statistics — they accumulate from the first bar of the chart's history, not from a recent window, so they are reference points, not "today's" reading.
  • Use the bottom-right table only as a reminder for the currently active mode — switch Reset Condition Type to read each mode's own blurb; the table does not list all nine at once.

1.4 How the Indicator Works

Inputs & their role — Dynamic MA

  • baseLen ("Base MA Length", integer, default 50, min 1): the shortest the moving-average length ever gets — its value the instant the counter resets to 1. Example: at 50, a just-reset MA is a plain SMA(50); at 20 it would be a faster SMA(20) at the same moment.
  • maxDynLen ("Max Dynamic Length", integer, default 350, min 1): the hard ceiling the length can never cross, however long the counter climbs. Example: with baseLen = 50, the length reaches 350 once the counter hits 301, and stays at 350 for any higher counter value.
  • counterbreak ("Counter Break (Reverse Threshold)", integer, default 70, min 1): the counter value at which growth stops. With Reverse Counter off it is really just an alias for how long the length keeps growing before the next maxDynLen cap (it does not stop growth by itself — see Flow 3). With Reverse Counter on, it is the peak of the sawtooth: the counter climbs 1→70, then counts back down 70→1, then climbs again, for as long as the condition's direction holds.
  • reverseCounter ("Reverse Counter After Break", tick box, default off): off = the counter grows without turning back (until maxDynLen caps the length); on = the sawtooth behaviour above.
  • trending_col ("Trend Confirmation Length", integer, default 10, min 1): the number of consecutive rising (or falling) bars of the filtered trend line needed before the MA line's own colour switches to lime/red. A separate input from "Trending Periods" below — the two can disagree (see the technical notes).
  • upcol / dncol / neucol (three colour swatches, one row, no titles, defaults lime / red / yellow 50% transparent): the three colours of the dynamic MA line itself. Colours only.

Inputs & their role — Dynamic Reset Mode

  • resetConditionType ("Reset Condition Type", drop-down, default Slope, options Slope / RSI / Volume / Bollinger / MACD / Stochastic / CCI / Momentum / None): picks which of the nine rules in Flow 2 decides whether the counter keeps climbing. Only the group below matching your choice actually affects the output; the others are simply unused. None freezes the counter at 1 forever, turning the whole indicator into a fixed SMA(baseLen).

Inputs & their role — the nine condition groups

  • Slope: slopeOB ("Slope Length", default 50) — how many bars back the dynamic MA is compared with itself to decide its slope.
  • RSI: rsiLength (default 14), and a paired overbought/oversold row where the first field ("RSI Overbought/Oversold", default 60) holds the overbought value rsiOB and the second, unlabelled field next to it (default 40) holds the oversold value rsiOS — this "value with no title, carrying the tooltip" layout repeats for Stochastic and CCI below.
  • Volume: volSmaLength ("Volume SMA Length", default 20) — despite its name this is actually used as a WMA length (see the technical notes for the hidden fixed comparison side).
  • Bollinger: bbLength (default 200) and bbMult ("Bollinger Multiplier", default 1.1) — the look-back and the standard-deviation multiplier of a Bollinger Band computed on close.
  • MACD: macdFast (default 50), macdSlow (default 100), macdSignal (default 25) — note these are far larger than a textbook 12/26/9 MACD, making this a slow, higher-timeframe-style reading.
  • Stochastic: stochLength (default 50) and the overbought/oversold pair stochOB / stochOS (defaults 60 / 40) — this is the raw %K only, with no extra smoothing.
  • CCI: cciLength (default 100) and the pair cciOB / cciOS (defaults 10 / −10) — a narrow band close to zero, not the classic ±100 "extreme" levels; see the notes on how often this flips.
  • Momentum: momentumLength (default 140) — the look-back of a rate-of-change calculation; only its sign (positive/negative) is used.

Inputs & their role — Trend & Signals / Table Display

  • length ("Trend smoother", default 20): the period fed into the two-pole smoothing filter that turns the dynamic MA into the slower "filtered trend" line. Before/after: 10 → a faster, twitchier filtered line; 50 → a slower, flatter one.
  • trendSmoothing ("Smoothing Weight", default 0.8, range 0.1–1.0): the damping factor of that same filter. Example: closer to 1.0 lets the filter follow the MA more closely (less lag, more wiggle); closer to 0.1 makes it noticeably smoother and slower.
  • trending ("Trending Periods", default 20, min 1): the number of consecutive rising (or falling) filtered-trend bars needed before the circles and triangles switch on. A separate threshold from "Trend Confirmation Length" above, which only affects the MA line's colour.
  • trendUp_col / trendDn_col / grad_col (three swatches, defaults lime / red / yellow): the gradient end-colours and the neutral/start colour for the circles and triangles — a separate colour set from upcol/dncol/neucol above, even though the defaults happen to match.
  • showGuidanceTable ("Show Reset Mode Guidance Table", default on) and trendStrengthTable ("Show Trend Strength Table", default on): independently show or hide the two tables. Display only.

Hard-coded constants (NOT inputs)

  • Circle/triangle offset: always an ATR(200) above or below the filtered-trend line — not adjustable.
  • Colour gradient range: the lime/red intensity of the circles and triangles always ramps between 10 and 50 consecutive bars, hard-coded — independent of both "Trend Confirmation Length" and "Trending Periods".
  • Volume reset's fixed side: the "Volume" condition always compares a hard-coded SMA(volume, 20) against the volSmaLength-based WMA — the 20 never follows the input.
  • The invisible helper line: visualclose = EMA(close, 10), plotted 100% transparent, exists only to anchor the fill between it and the MA line.
  • Start-marker offset: the trend-start triangles are drawn with offset = -1 (one bar back).
  • Table layout: the top-right table is 4 columns × 6 rows (one row left blank for spacing) at position.top_right; the bottom-right table is 3 columns × 2 rows at position.bottom_right. Both are redrawn only on the last bar.
  • Limits: max_lines_count = 500, max_boxes_count = 500, max_bars_back = 500 — generous ceilings the script's plots/shapes/tables never come close to using.

Main logic blocks

⏱️ Flow 0 — Order of work on every candle

  • ① compute a provisional MA using last bar's counter → ② read the chosen condition into currentState using that provisional MA → ③ update the counter from currentState → ④ recompute the final MA with the updated counter (this is what gets plotted) → ⑤ smooth it into the filtered trend line → ⑥ count consecutive up/down runs and set colours → ⑦ update the close-vs-MA fill → ⑧ draw circles/triangles → ⑨ update the trend score and the two tables.

📐 Flow 1 — The provisional dynamic MA (before this bar's update)

  • dynLen = min(baseLen + (counter − 1), maxDynLen) and ma = SMA(close, dynLen), using whatever counter was left over from the previous bar (it is a running value, not reset here). This provisional ma is what the "Slope" condition in Flow 2 compares against — the counter itself is only updated afterwards, in Flow 3.

🎯 Flow 2 — Reading the chosen condition into currentState

  • Exactly one of the nine rules below runs, based on Reset Condition Type. Each produces +1 (bullish/agrees), −1 (bearish/agrees the other way) or 0 (neutral).
  • Slope: ma > ma[slopeOB] → 1, ma < ma[slopeOB] → −1, else 0. Note: ma[slopeOB] is not a fixed 50-bar-back SMA(50) reading — it is whatever this same adaptive series happened to equal 50 bars ago, computed with whatever length the counter had assigned at that time (see the technical notes).
  • RSI: rsiValue > rsiOB → 1 (e.g. RSI 64 > 60), rsiValue < rsiOS → −1 (e.g. RSI 35 < 40), else 0 (the 40–60 zone is neutral).
  • Volume: SMA(volume, 20) > WMA(volume, volSmaLength) → 1, the reverse → −1, else 0.
  • Bollinger: close > bbUpper → 1, close < bbLower → −1, else 0 (inside the bands is neutral).
  • MACD: macdLine > signalLine → 1, the reverse → −1, else 0.
  • Stochastic: %K > stochOB → 1 (e.g. 65 > 60), %K < stochOS → −1 (e.g. 32 < 40), else 0.
  • CCI: CCI > cciOB → 1 (e.g. CCI 25 > 10), CCI < cciOS → −1 (e.g. CCI −18 < −10), else 0. With the default ±10 band — far tighter than the usual ±100 "extreme" levels — CCI spends relatively little time exactly at 0, so this mode tends to stay directional (non-zero) often, but can still flip sign from one bar to the next quite easily.
  • Momentum: ROC(close, 140) > 0 → 1, < 0 → −1, 0 only on the rare exact-zero reading.
  • None: always 0.

🔁 Flow 3 — Updating the counter

  • If currentState = 0 (neutral, in any mode — including always, in "None"): the counter resets to 1 and the sawtooth direction resets to "increasing". This happens regardless of the Reverse Counter setting.
  • If currentState differs from the previous bar's state (a direction flip, e.g. was +1, now −1): same reset — counter back to 1.
  • If currentState matches the previous bar's state (the condition still agrees):
    • Reverse Counter off: counter += 1 every such bar, without limit (the length itself is still capped by maxDynLen). Example: 40 consecutive agreeing bars → counter 40 → dynLen = 50 + 39 = 89.
    • Reverse Counter on: the counter climbs 1 → counterbreak (e.g. 1 → 70), then switches to counting back down to 1, then switches again and climbs — a repeating sawtooth, for as long as the condition keeps agreeing. Example (counterbreak = 70): counter goes 1,2,…,70 (dynLen 50→119), then 69,68,…,1 (dynLen back down to 50), then climbs again — a period of about 138 bars, entirely reset if the condition ever disagrees or goes neutral in between.

📏 Flow 4 — The final dynamic MA (what gets plotted)

  • dynLen and ma are recalculated with the updated counter from Flow 3 — this second value is the one drawn on the chart and used everywhere downstream.

🌊 Flow 5 — Smoothing the MA into the filtered trend line

  • A two-pole low-pass filter (length and trendSmoothing) is applied to the final ma, producing filteredTrend — the average of a fast internal stage and a slower one built from it. This line is never plotted; it exists only to drive direction, colouring and marker placement.

📈 Flow 6 — Counting consecutive up/down runs and the colour gradient

  • isUptrend = filteredTrend > filteredTrend[2], isDowntrend = filteredTrend < filteredTrend[2] — compared to the value two bars back, not one.
  • If isUptrend: trendUp += 1 and trendDown resets to 0 the same bar. If isDowntrend: the mirror image. On a flat bar (neither true — filteredTrend == filteredTrend[2] exactly), both counters simply hold their current values — a pause, not a reset.
  • trendColor: while in an up-run, a gradient from yellow (trendUp = 10 or below) to lime (trendUp = 50 or above), hard-coded to that 10–50 range regardless of the "Trending Periods" or "Trend Confirmation Length" settings; the mirror gradient (yellow → red) applies in a down-run; flat bars keep plain yellow.

🚦 Flow 7 — Two separate "confirmed trend" checks

  • For the circles and triangles: confirmedUptrend = (trendDown ≥ trending) and confirmedDowntrend = (trendUp ≥ trending). Despite the names, confirmedUptrend is driven by the down-run counter and vice versa — but the shapes that use them are titled the other way round again ("Trending Up" is drawn when confirmedDowntrend is true, "Trending Down" when confirmedUptrend is true), so in plain market terms the titles end up correct: a circle titled "Trending Up" really does appear once trendUp (the up-run counter) has reached trending bars. See the technical notes for the full chain.
  • For the MA line's own colour: confirmedUptrend_col = (trendUp ≥ trending_col) and confirmedDowntrend_col = (trendDown ≥ trending_col) — this pair is named the plain way (Up uses the up-counter). trending_col ("Trend Confirmation Length", default 10) is usually much smaller than trending ("Trending Periods", default 20), so the MA line's colour typically confirms a trend well before the circles/triangles do.
  • Placement: circleup = filteredTrend + ATR(200), circledn = filteredTrend − ATR(200). The "Trending Up" circle sits below the line (circledn), the "Trending Down" circle above it (circleup) — support-style and resistance-style placement respectively.
  • Trend-start triangles: PosTrendStart = confirmedUptrend and not confirmedUptrend[1] (first bar the down-run counter reaches the threshold) draws a down-pointing triangle at circleup titled "Trend Up"; NegTrendStart is the mirror, an up-pointing triangle at circledn titled "Trend Dn". Each is followed by two larger, more transparent duplicate shapes purely for a glow effect.

🖍️ Flow 8 — The separate close-vs-MA trend (fill colour only)

  • A simple boolean trend flips to true on ta.crossover(close, ma) and to false on ta.crossunder(close, ma) — this is completely independent of the filtered-trend/counter system above. It only decides whether the fill between the MA line and the invisible visualclose is tinted lime or red. A trend_change flag is computed alongside it but is never used anywhere else in the script.

🧮 Flow 9 — Trend score and the two tables

  • trendScore = (counter − 1) / (counterbreak − 1) × 100. Example: counter = 36, counterbreak = 70 → (35 ÷ 69) × 100 ≈ 51.
  • highestTrendScore and averageTrendScore accumulate from the very first bar of the chart's history and are never reset — they are lifetime statistics, recalculated on every bar, and simply displayed as of the last bar.
  • Top-right table (shown when trendStrengthTable is on): Reset Condition, Counter Value, Trend Strength, Highest Trend Score, Average Trend Score (one spacer row in between).
  • Bottom-right table (shown when showGuidanceTable is on): header row plus a single data row describing only the currently selected Reset Condition — its typical user ("Best For") and its key benefit, picked from nine pre-written descriptions baked into the script.

Outputs & their role in trading

  • The dynamic MA line + fill: a trend/range gauge whose own smoothness tells you how long the chosen condition has agreed with itself.
  • Circles and triangles: a separately-tuned confirmation layer marking sustained directional runs and their starting bar.
  • The two tables: a live read-out of the current reset mode, the counter's progress and its historical extremes, plus a one-line reminder of what the active mode is good for.
💡 Important technical notes:
  • Two different "how many bars confirm a trend" settings exist, plus a third hard-coded one. The MA line's colour uses trending_col (default 10); the circles/triangles use trending (default 20); the gradient intensity of the circles/triangles ramps over a fixed 10–50 bar range that neither input touches. The three can easily be mistaken for one setting.
  • "confirmedUptrend"/"confirmedDowntrend" are named the opposite way round from "confirmedUptrend_col"/"confirmedDowntrend_col". The first pair (circles/triangles) is driven by the opposite run counter from what its name suggests (confirmedUptrend reads trendDown); the second pair (MA line colour) is named the straightforward way. The plotshape titles for the first pair ("Trending Up"/"Trending Down"/"Trend Up"/"Trend Dn") are themselves written to match the real market direction, not the variable name — so trust the shape titles and trendColor's own direction, not the raw variable names, if reading the source.
  • ma[slopeOB] is a moving target, not a fixed-length lookback. Because the plotted ma series had whatever dynamic length the counter assigned on each historical bar, "the MA value 50 bars ago" may have been computed with a completely different length back then (anywhere from baseLen up to maxDynLen). The Slope condition's comparison is therefore not an apples-to-apples "50-bar slope of a 50-length SMA".
  • The Volume condition's SMA side ignores the Volume SMA Length input. It always compares a hard-coded SMA(volume, 20) against the input-driven WMA(volume, volSmaLength) — changing the input only moves one side of the comparison.
  • "RSI/Stochastic/CCI Overbought/Oversold" is really two inputs sharing one row. The titled field holds the overbought value; the blank field right next to it (carrying the detailed tooltip) holds the oversold value. Easy to overlook in Settings.
  • CCI's default band is ±10, not the conventional ±100. This is a narrow zone close to zero, so with default settings the CCI mode's currentState can change sign more often than the other modes with their wider defaults.
  • Flat bars pause both run counters without resetting either. When filteredTrend exactly equals its value two bars back, trendUp and trendDown both simply hold their last value for that bar; confirmation thresholds already met stay met.
  • The close-vs-MA trend flag only colours the fill. It is unrelated to the counter/filtered-trend system that drives the line colour, circles and triangles — the fill can be lime while the circles are still signalling a down-run, or vice versa. trend_change is computed but used nowhere.
  • Choosing "None" disables the adaptive mechanism entirely. currentState is always 0, so the counter never leaves 1 and the "dynamic" MA is permanently a plain SMA(baseLen).
  • Both tables are lifetime/last-bar only. They draw solely on barstate.islast (standard and expected for tables), but highestTrendScore/averageTrendScore specifically reflect the entire loaded history, not a recent window — on a very long chart they can differ a lot from what the counter has been doing lately.
Zoom/Pan Layered Image
Background Overlay
− +

The indicator above just became a TRADING BOT — 1 AI click

📊Original indicator
→
🤖AI 1-click convert
→
⚙️Bot trading 24/7