AI Source Switching Moving Average (Zeiierman)█ Overview
The AI Source Switching Moving Average is an adaptive price-selection and trend intelligence system that combines historical analog recognition, machine learning classification, neural learning, feature optimization, dynamic source selection, and AI-driven trend management into a single framework.
Rather than calculating a moving average from a fixed source such as Close, Open, High, or Low, the indicator continuously evaluates which price source currently contains the most useful market information.
The script transforms each OHLC source into a multi-dimensional feature space, stores historical behavior, searches for similar historical environments, and allows those analogs to vote on which source currently provides the highest predictive value.
An adaptive feature-weighting engine continuously learns which characteristics best separate bullish and bearish conditions, while an online neural model adds a second layer of directional intelligence.
█ Why Is This One Unique
Most moving averages are static.
You select a source:
• Close
• Open
• High
• Low
Then the moving average simply smooths that source. This indicator does something fundamentally different.
Instead of assuming one source is always optimal, it continuously evaluates all four OHLC streams and determines which source currently contains the strongest information based on historical behavior.
The indicator effectively asks:
"Which price source has historically produced the best outcome under conditions most similar to the current market?"
That selected source then becomes the input for the moving average and AI Supertrend. This transforms a traditional moving average into a dynamic source-selection engine.
█ How It Works
⚪ Builds Multi-Dimensional OHLC Features
The model does not analyze raw prices directly.
Each OHLC source is transformed into a behavioral fingerprint consisting of:
• Trend Structure
• Mean-Reversion State
• Momentum
• Volatility Profile
• Range Position
• Price Slope
Every source becomes its own market state representation.
oT = featTrend(open, atrNow)
oM = featMean(open)
oMo = featMomentum(open)
oV = featVol(open)
oR = featRange(open)
oS = featSlope(open, atrNow)
The same feature process is applied to High, Low, and Close.
hT = featTrend(high, atrNow)
lT = featTrend(low, atrNow)
cT = featTrend(close, atrNow)
Instead of asking:
"Where is price?"
The model asks:
"How is this source behaving?"
⚪ Creates A Historical Memory Bank
Every confirmed bar is stored together with:
• Source feature state
• Future market outcome
• Volatility-normalized labels
This becomes the learning dataset.
moveFwd = close - close
bandFwd = learnAtrFactor * atrNow
outcome = moveFwd > 2 * bandFwd ? 3 :
moveFwd > bandFwd ? 2 :
moveFwd > 0 ? 1 :
moveFwd < -2 * bandFwd ? -3 :
moveFwd < -bandFwd ? -2 :
moveFwd < 0 ? -1 : 0
Each stored row contains the feature snapshot plus the outcome label.
rowO = makeRow(oT , oM , oMo , oV , oR , oS , outcome)
Each confirmed observation becomes a real historical example the model can reference later.
if barstate.isconfirmed and bar_index > horizonBars + 120
if validO
addBank(bankO, rowO, memoryDepth)
addBank(bankAll, rowO, memoryDepth * 4)
⚪ Uses Historical Analog Matching
Once enough data has been collected, the model begins searching for historical situations that resemble current conditions.
Similarity is measured using a compressed Lorentzian-style distance function:
compress(d) =>
math.log(1.0 + math.abs(d))
The gap between the current feature state and each historical row is then calculated across all features.
gapTo(t, m, mo, v, r, s, array row) =>
wT * compress(t - row.get(0)) +
wM * compress(m - row.get(1)) +
wMo * compress(mo - row.get(2)) +
wV * compress(v - row.get(3)) +
wR * compress(r - row.get(4)) +
wS * compress(s - row.get(5))
This helps reduce outlier influence and prevents any single feature from dominating the comparison process.
The goal is not to find identical charts. The goal is to find historically similar market environments.
⚪ Let Historical Analogs Vote
After finding the closest historical examples, the model allows them to vote.
Closer analogs receive greater influence. More distant analogs contribute less.
wg = 1.0 / (1.0 + g)
score += cls * wg
bull += cls > 0 ? wg : 0.0
bear += cls < 0 ? wg : 0.0
The weighted voting system produces:
• Analog Score
• Directional Bias
• Agreement Fraction
• Similarity Tightness
• Market Conviction
analog = total > 0 ? score / total : 0.0
dir = analog > 0.15 ? 1 : analog < -0.15 ? -1 : 0
agree = total > 0 ? (dir == 1 ? bull : dir == -1 ? bear : 0.0) / total : 0.0
tight = clamp(1.0 - avgGap / gapScale, 0.0, 1.0)
This creates a probabilistic ranking system rather than a binary signal engine.
⚪ Auto-Optimizes Feature Importance
Different markets reward different behaviors.
A feature that is extremely predictive today may become less useful tomorrow. The indicator solves this problem using adaptive Fisher-discriminant optimization.
The engine continuously measures which features best separate bullish outcomes from bearish outcomes.
f = math.pow(meanB - meanS, 2) / (varB + varS + 0.000001)
• Features with higher predictive value receive larger weights.
• Features with lower predictive value gradually lose influence.
norm = maxF > 0 ? fish.get(j) / maxF : 1.0
imp.set(j, math.max(floor, norm * 8.0))
The optimized weights are smoothed over time.
wAuto.set(j, prev + fisherSpeed * (wRaw.get(j) - prev))
This allows the model to adapt automatically without requiring manual optimization.
⚪ Adds Neural Learning
Beyond analog classification, the indicator includes an online neural learning layer.
The neural model continuously updates itself using confirmed market outcomes and adjusts internal directional bias over time.
neuralScore(t, m, mo, v, r, s) =>
nt * t + nm * m + nmo * mo + nv * v + nr * r + ns * s + nb
The neural layer evaluates:
• Trend Structure
• Mean Reversion
• Momentum
• Volatility
• Range Position
• Slope Behavior
Training is performed using an Adam-style optimizer.
adam(weight, grad, mom, vel, step) =>
newMom = beta1 * mom + (1.0 - beta1) * grad
newVel = beta2 * vel + (1.0 - beta2) * grad * grad
mHat = newMom / (1.0 - math.pow(beta1, step))
vHat = newVel / (1.0 - math.pow(beta2, step))
newWeight = weight - learnRate * mHat / (math.sqrt(vHat) + eps)
This creates a second intelligence layer that works alongside the analog engine.
⚪ Ranks All Four Sources
Every bar receives independent scores for:
• Open
• High
• Low
• Close
rO = rankSource(oT, oM, oMo, oV, oR, oS, oAnalog, oAgree, oTight, oK)
rH = rankSource(hT, hM, hMo, hV, hR, hS, hAnalog, hAgree, hTight, hK)
rL = rankSource(lT, lM, lMo, lV, lR, lS, lAnalog, lAgree, lTight, lK)
rC = rankSource(cT, cM, cMo, cV, cR, cS, cAnalog, cAgree, cTight, cK)
The ranking combines:
• Analog Classification Strength
• Historical Agreement
• Similarity Quality
• Feature Separation
• Neural Confidence
rankSource(t, m, mo, v, r, s, analog, agree, tight, k) =>
neural = useNeural ? neuralScore(t, m, mo, v, r, s) : 0.0
directional = math.abs(analog) / 3.0
raw = directional * 0.35 + agree * 0.25 + tight * 0.20 + normScore(neural) * neuralInfluence + (k >= kNeighbors ? 0.10 : 0.0)
clamp(raw, 0.0, 1.0)
The highest-ranked source becomes the active source for both the moving average and Supertrend.
bestId = safeRO >= safeRH and safeRO >= safeRL and safeRO >= safeRC ? 0 :
safeRH >= safeRL and safeRH >= safeRC ? 1 :
safeRL >= safeRC ? 2 : 3
This means the indicator can dynamically switch between Open, High, Low, and Close depending on which source currently demonstrates the strongest historical edge.
⚪ Builds An Adaptive AI Moving Average
After selecting the best source, the indicator calculates a moving average using that dynamically chosen input.
hardSrc = bestId == 0 ? open :
bestId == 1 ? high :
bestId == 2 ? low : close
The selected source is then smoothed and passed into the moving-average engine.
aiSourceRaw = hardSrc
aiSource = ta.ema(aiSourceRaw, srcSmoothLen)
aiMA = ma(aiSource, maLen, maType)
Unlike traditional averages that remain tied to a fixed source, the AI MA continuously adapts to changing market conditions.
The result is a smoother and more context-aware trend representation.
█ Main Weakness
The indicator is not deep learning.
It does not train a large neural network.
Instead, it operates as an online analog classifier enhanced by adaptive feature weighting and lightweight neural optimization.
Because it learns from historical analogs, performance can vary depending on:
• Symbol
• Timeframe
• Market Regime
• Memory Depth
• Feature Configuration
• Learning Horizon
As with all adaptive systems, historical similarity does not guarantee future outcomes.
█ How To Use
⚪ Reading The AI Moving Average
• Rising average = bullish conditions dominate.
• Falling average = bearish conditions dominate.
• Strong slope = stronger trend conviction.
• Flat slope = weaker directional conviction.
The AI Moving Average can be used much like a traditional moving average, but with the added benefit of dynamic source selection.
Use it for:
• Identifying trend direction
• Spotting trend changes
• Confirming momentum shifts
• Dynamic support and resistance analysis
• Pullback and retest opportunities
• Trend continuation setups
In bullish conditions , traders may look for price to remain above the moving average and use pullbacks into the average as potential continuation zones.
In bearish conditions , traders may look for price to remain below the moving average and use rallies into the average as potential resistance areas.
⚪ Reading The AI Supertrend
The AI Supertrend acts as:
• Trend Filter
• Dynamic Trailing Stop
• Market Structure Guide
• Bullish flips indicate positive trend conditions.
• Bearish flips indicate negative trend conditions.
Because the band width adapts to model confidence, trend changes become more responsive during strong conditions and more tolerant during weak conditions.
Use the AI Supertrend for:
• Trend confirmation
• Trade management
• Trailing stop placement
• Exit planning
• Market structure analysis
• Trend-following systems
Many traders may choose to remain long while price stays above the bullish trail and remain short while price stays below the bearish trail.
The Supertrend can also be used as a dynamic stop-loss framework, allowing positions additional room during uncertain conditions while tightening risk management when the AI model detects stronger directional conviction.
█ Settings
MA Type: Selects the moving average formula used after source selection.
MA Length: Controls the smoothing period of the AI moving average.
AI Source Smoothing: Smooths source transitions after source switching.
Memory Depth: Controls how many historical examples are stored.
Analog Count: Controls how many historical analogs participate in voting.
Learning Horizon: Controls how far ahead outcomes are evaluated.
Analog Spacing: Controls sampling diversity within the memory bank.
Learning Sensitivity × ATR: Controls how future outcomes are classified.
Use Neural Online Training: Enables the adaptive neural learning layer.
Neural Influence: Controls neural contribution to source ranking.
Learning Rate: Controls neural adaptation speed.
Huber Delta: Controls error sensitivity during training.
Auto Optimize Feature Weights: Enables adaptive feature importance learning.
Adaptation Speed: Controls weight adjustment speed.
Weight Floor: Sets minimum feature influence.
Minimum Rows: Controls when Fisher optimization becomes active.
Show AI Supertrend: Displays the adaptive trail.
ATR Length: Controls volatility measurement.
ATR Multiplier: Controls trail width.
AI Band Adaptivity: Controls AI influence over trail width.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicateur Pine Script®






















