Trend Signals [QuantAlgo + Quantum & Fractal Engine]

vecnfaf5 · study · 714 行 · 点赞 31 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vecnfaf5
 
//@version=6
indicator("Trend Signals [QuantAlgo + Quantum & Fractal Engine]", overlay = true)
 
 
// ═══════════════════════════════════════════════════════════════════════════
// vecnfaf5,часть идеи взята у QuantAlgo- спасибо.....Part of the idea was taken from QuantAlgo—thanks.
//              ╔════════════════════════════════╗              //
//              ║      USER-DEFINED SETTINGS     ║              //
//              ╚════════════════════════════════╝              //
 
var string ewmac_settings      = "════════ EWMAC & Math Settings ════════"
var string engine_settings     = "════════ Smoothing Engine Parameters ════════"
var string volatility_settings = "════════ Volatility Settings ════════"
var string score_settings      = "════════ Score Settings ════════"
var string signal_settings     = "════════ Signal Settings ════════"
var string htf_settings        = "════════ Higher Timeframe (HTF) Filter ════════"
var string visual_settings     = "════════ Visualization Settings ════════"
 
// ───────────────────────────── Tooltips ─────────────────────────────
 
tooltip_preset        = "Ready-made sets for trading style.\n\nDefault — everything comes from manual settings below.\n\nFast Response (rules 1-4, entry 2.5) — fast EWMAC pairs for intraday (5 min – 1 hour).\n\nSmooth Trend (rules 4-6, entry 6.0) — slow pairs for positional trading (D/W).\n\nPresets override: set of active rules, volatility period, long-term volatility weight and length, adaptive scaling length, entry threshold and exit fraction. Rule lengths, weights and all engine parameters stay manual."
tooltip_src           = "Price data for EWMAC rules, volatility estimation and the trend line. Close — closing price; hl2, hlc3, ohlc4 average more bar information and produce lower volatility. Designed for series above zero (stocks, crypto, forex, indices). Spreads and series that can be ≤ 0 are not supported."
tooltip_ma            = "Internal smoothing algorithm of each fast/slow pair.\n\nEMA — classic EWMAC.\nSMA, WMA — classic lagging averages (in SMA window equals length, in WMA weights linearly decrease).\nRMA — Wilder's average (α = 1/length): roughly EMA twice as long, so the same lengths give a slower filter.\nHMA — Hull MA, fast, lag almost zero.\nLSMA — endpoint of linear regression: no lag on trend, overshoots on reversals.\nVWMA — volume-weighted average (needs volume in instrument data).\nALMA — Gaussian window with offset (Offset and Sigma parameters in engine group), small lag.\nDEMA, TEMA — double and triple EMA: small lag, overshoots.\nZLSMA — LSMA with additional lag compensation.\nMcGinley — dynamic average, adapts speed to price position.\nUltSmooth — Ehlers' UltimateSmoother: flat passband, almost zero lag.\nT3 — Tillson's average smoothed by six EMAs (parameter 'T3: Volume Coefficient'), lagging but smooth.\nJurik — open JMA approximation (phase and power parameters), smooth, small lag.\nKalman2State — two-state Kalman filter (level + velocity): almost lag-free on trend, for 'Fast Slope' mode.\nZLEMA — EMA with lag compensation.\nKAMA — adaptive by trend efficiency (ER).\nQASE — adaptive alpha-beta filter (tracks price velocity).\nKalman — Kalman level filter; at Sensitivity 1.0 behaves like EMA of the same length, but with fast warm-up.\nGaussian Fractal — FRAMA: adaptation by fractal dimension.\nTRAMA Classic / Modern — adaptive by ER averages.\nRLS2 — stable alpha-beta filter.\nLaguerreF — UltimateSmoother + Laguerre filter.\n\nImportant: EWMAC score is proportional to the DIFFERENCE OF LAGS of fast and slow. Lag-free engines on trends (ZLEMA, QASE, RLS2, LaguerreF with prefilter) give score ≈ 0 on a clean trend. Adaptive ones (KAMA, TRAMA, Fractal) accelerate on trends and also weaken the signal. This is true for 'Fast - Slow' score mode. In 'Fast Slope' mode (score group), lag does not matter, low-lag engines also fit; 'Price Deviation from fast' mode requires lagging MAs, like the classics. Low-lag ones (HMA, LSMA, ZLSMA, DEMA, TEMA, UltSmooth, ZLEMA) in classics give score ≈ 0 — use them with 'Fast Slope' mode. For classics, EMA, SMA, WMA, RMA, VWMA, ALMA, McGinley, T3, Jurik, Kalman (essentially EMA) and LaguerreF without prefilter fit."
tooltip_power         = "Affects QASE and TRAMA.\n\nQASE: higher — higher α ceiling (faster on trends).\nTRAMA Classic: α = ER^Power, higher Power = slower in noise.\nTRAMA Modern: affects both the ER^Power curve and the α ceiling.\n\nDoes not affect EMA, ZLEMA, Kalman, RLS2, KAMA, Fractal, Laguerre."
tooltip_slowmult      = "How many times the slow average is longer than the fast one in each pair. Classic EWMAC — 4. Changes all pairs at once. Fixed scaling (parameter below) is tuned for 4; for other values it's better to use Adaptive scaling."
tooltip_rule1         = "The fastest EWMAC pair. Slow period = fast × Slow/fast multiplier. Reacts to the shortest price fluctuations and reverses first. Weight 0 excludes the rule from the score and the trend line."
tooltip_rule2         = "Short-term EWMAC pair. Tracks short movements and reacts early to new trends. Weight 0 excludes the rule from the score and the trend line."
tooltip_rule3         = "Medium-short-term EWMAC pair. Follows developing trends but still reacts to short fluctuations. Weight 0 excludes the rule."
tooltip_rule4         = "Medium-term EWMAC pair. Main trend-following element. Included in both presets. Weight 0 excludes the rule."
tooltip_rule5         = "Medium-long-term EWMAC pair. Follows sustained trends and filters short fluctuations. Weight 0 excludes the rule."
tooltip_rule6         = "The slowest EWMAC pair. Holds the global direction the longest and reverses last. Weight 0 excludes the rule."
 
tooltip_adaptfloor    = "Lower bound of α for adaptive engines (KAMA, TRAMA Classic, Gaussian Fractal) = 2/(length+1), meaning the filter is never slower than EMA of its length.\n\nWithout this, fast and slow pairs of such an engine differ only in ER window, and the fast − slow difference is almost zero.\n\nOff — original behavior: KAMA with lower bound by 'KAMA: Slow Period' and squared coefficient, TRAMA Classic with α = ER^Power without floor, Fractal with the minimum of 'Fractal: Min α'."
tooltip_boost         = "QASE and TRAMA Modern: upper bound of α = α_min × (1 + Boost × Power), but not above the α Cap. Higher — faster response on strong trend (high ER)."
tooltip_capalpha      = "α ceiling for QASE and TRAMA Modern. 0.8 by default; closer to 1 — the filter almost fully follows the price on strong trends."
tooltip_betamul       = "Velocity coefficient β multiplier in alpha-beta filters QASE and RLS2: β = Multiplier × α² / (2 − α). 1.0 — standard. Higher — stronger trend response, but also more overshoot on reversals; lower — calmer, closer to regular EMA."
tooltip_kalsens       = "Kalman: sensitivity (process noise Q multiplier). At 1.0 the steady-state filter gain equals α = 2/(length+1), like EMA of the same length. Higher than 1 — faster and noisier, lower than 1 — smoother but with more lag."
tooltip_kalp0         = "Kalman: initial error covariance P0. Large value — fast convergence in the first bars (warm-up), small — the filter adjusts slower at the beginning of history. Does not affect the steady-state mode."
tooltip_kamafast      = "KAMA: fast period for upper bound of α = 2/(N+1). Classic — 2."
tooltip_kamaslow      = "KAMA: slow period for lower bound of α (classic — 30). Used only when 'α Floor by Length' is off."
tooltip_frack         = "Gaussian Fractal: coefficient K in the formula α = exp(−K × (D − 1)), where D is the fractal dimension. Classic FRAMA — 4.6. Higher — α falls faster in noisy sections."
tooltip_fracmin       = "Gaussian Fractal: minimum α value (classic 0.01). When 'α Floor by Length' is on, the greater of this value and 2/(length+1) is used."
tooltip_fracmax       = "Gaussian Fractal: maximum α value. 1.0 — the filter can fully follow the price."
tooltip_fracd         = "Gaussian Fractal: fractal dimension value when the window is degenerate (zero range). 1.5 — neutral."
tooltip_frachl        = "Gaussian Fractal: calculate dimension by High/Low (classic FRAMA). Off — by the selected price source."
tooltip_lagpre        = "LaguerreF: pre-smooth the price through UltimateSmoother (period = length × Multiplier), then through the Laguerre filter with a fixed γ.\n\nOff — pure Laguerre without prefilter; γ is then derived from the length: γ = 1 − 2/(length × Multiplier + 1), so that fast and slow differ. For EWMAC the prefilter is NOT recommended: it removes lag, and score measures precisely the lag (with prefilter score ≈ 0 on trends)."
tooltip_laggamma      = "LaguerreF: γ (0.0–0.99). Lower — faster response, higher — more smoothing and lag. Used only when prefilter is enabled."
tooltip_lagmul        = "LaguerreF: length multiplier. With prefilter — UltimateSmoother period = length × Multiplier. Without prefilter — in the formula γ = 1 − 2/(length × Multiplier + 1)."
 
tooltip_almaoff       = "ALMA: Gaussian window offset (0–1). Closer to 1 — less lag but more noise; closer to 0 — window deeper in history, more smoothing. Classic 0.85."
tooltip_almasig       = "ALMA: Gaussian window width (σ). Higher — window closer to uniform (similar to SMA), lower — sharper, more weight to recent bars. Classic 6."
tooltip_mcgk          = "McGinley Dynamic: coefficient K in the denominator K × length × (price/MD)^4. Classic 0.6 (faster than 1.0). Denominator is floored at one to prevent overshoot."
tooltip_t3v           = "T3: volume coefficient (0–1). 0 — T3 becomes triple EMA, 0.7 — classic (less lag, soft overshoots), closer to 1 — stronger overshoots."
tooltip_jurphase      = "Jurik: phase (−100…100). Lower — smoother and with more lag, higher — faster and with overshoots. 0 — neutral."
tooltip_jurpow        = "Jurik: smoothing power (1–5). Higher — more smoothing and lag. Classic 2."
tooltip_k2sens        = "Kalman2State: process noise Q multiplier. Q is derived from the length so that the level gain approximately equals EMA of the same length; 1.0 — this mode. Higher than 1 — faster and noisier, lower — smoother. The filter also estimates price velocity, so on trend it is almost lag-free: for 'Fast Slope' score mode and HTF filter, not for classics."
tooltip_vol_len       = "Realized volatility estimation window (in bars). Short (16-24) — quickly follows volatility changes but noisier. Long (48-64) — more stable risk unit."
tooltip_blend_weight  = "Share of long-term average volatility in the final estimate. 0 — short window only. Higher — estimate reacts less to spikes and lulls."
tooltip_blend_len     = "Long-term volatility averaging window. While there are not enough bars, only the short window is used. Has no effect at weight 0."
 
tooltip_scaling_mode  = "Method of scaling rules to a common scale. Adaptive — by each rule's recent history on the current instrument. Fixed — by formula from the fast MA length, the same across the whole history and on all instruments."
tooltip_scaling_len   = "Adaptive scaling window. Shorter (100-150) — fast recalibration, longer (400-750) — more stable. While the window is not filled, Fixed is used. Only works in Adaptive mode."
tooltip_multiplier    = "Diversification multiplier. 0 — auto by number of active rules (1.00 for one rule … 1.36 for six). Greater than 0 — manual value; 1.00 leaves the score as a simple weighted average."
tooltip_score_cap     = "Maximum absolute value of each rule's score and the total score. Keep it above the Entry Threshold, otherwise signals cannot confirm."
tooltip_scoremode     = "How the raw score of each rule is calculated (before volatility normalization).\n\nFast - Slow (classic) — difference between fast and slow averages. Measures the difference of lags, so LAGGING MAs are needed (EMA, SMA, WMA, RMA, Kalman, LaguerreF without prefilter).\n\nFast Slope — change of the fast average over the slope window. Lag does not matter, low-lag MAs also work (ZLEMA, QASE, RLS2, HMA, etc.). The slow average does not participate in the score (it is only needed for the trend line).\n\nPrice Deviation from fast — distance from price to the fast average. Like classics, it measures lag: with low-lag MAs on trend it gives ≈ 0.\n\nIn 'Slope' and 'Deviation' modes the Fixed scale is not calibrated — use Adaptive. Re-tune the Entry Threshold and Exit Fraction."
tooltip_slopebars     = "Slope window in bars: score = fast − fast[window]. 0 — window equals fast rule length. Shorter — faster response but noisier. Used only in 'Fast Slope' mode."
tooltip_scaletarget   = "Target mean |score| after scaling (classic 10). The Entry Threshold is measured in these units: at 10, a threshold of 5 requires 50% of typical trend strength. Changes the meaning of the threshold, but not the shape of the signal."
tooltip_fixedscale    = "Numerator of the fixed multiplier: scale = N / √(fast MA length). Classic 15. Used in Fixed mode and until the Adaptive window is filled. Tuned for slow/fast ratio = 4."
 
tooltip_entry         = "Score level to confirm bullish/bearish signal. Mean |score| equals 'Target Mean', so the threshold reads directly. Lower (2-3) — earlier and more often, higher (6-8) — rarer and later."
tooltip_neutral_state = "Enable neutral state: the signal resets to neutral when the score rolls back beyond the exit level. Off — each signal holds until the opposite entry threshold."
tooltip_exit_frac     = "Exit level as a fraction of the Entry Threshold (hysteresis). At threshold 6.0 and fraction 0.50, a bullish signal resets below 3.0. Lower (0.25-0.35) — signal holds deeper in fading, higher (0.70-0.90) — resets earlier. Only works with neutral state."
 
tooltip_usehtf        = "Blocks new signals against the higher timeframe direction. Only the last CLOSED HTF bar is used (no repaint), so the filter lags at most one HTF bar. HTF must be strictly higher than the current timeframe — otherwise the filter automatically disables."
tooltip_htfres        = "Higher timeframe of the filter (e.g. 240 = 4 hours, D = day). Must be higher than the chart timeframe."
tooltip_htfalg        = "Average algorithm on the higher timeframe. Engine parameters are taken from the 'Smoothing Engine Parameters' group."
tooltip_htflen        = "Average length on the higher timeframe."
 
tooltip_color_preset  = "Ready color schemes. Custom uses the colors below; other presets use gray for the neutral state."
tooltip_bullish       = "Color of the line, glow, label, bars and background on bullish signal. Used only in Custom mode."
tooltip_bearish       = "Color of the line, glow, label, bars and background on bearish signal. Used only in Custom mode."
tooltip_neutral_color = "Color in neutral state, including the period before the first signal. Used only in Custom mode."
tooltip_line_width    = "Thickness of the main trend line."
tooltip_glow          = "Neon glow around the line: two layers with different thickness and transparency."
tooltip_glow_w1       = "Thickness of the outer glow layer."
tooltip_glow_w2       = "Thickness of the inner glow layer."
tooltip_glow_t1       = "Transparency of the outer glow layer (0 — opaque, 100 — invisible)."
tooltip_glow_t2       = "Transparency of the inner glow layer (0 — opaque, 100 — invisible)."
tooltip_readout       = "Signal status label (Bullish / Bearish / Neutral) at the end of the line. Anchored to the last closed bar. Signals and alerts work even when the label is hidden."
tooltip_readout_size  = "Size of the status label text."
tooltip_barcolor      = "Color price bars with the current signal color."
tooltip_bartrans      = "Bar color transparency. Lower (0-30) — saturated, higher (70-90) — delicate tint."
tooltip_bgcolor       = "Color the chart background with the current signal color."
tooltip_bgtrans       = "Background color transparency. Lower (50-70) — noticeable, higher (85-95) — barely visible."
 
// ───────────────────────────── Inputs: EWMAC ─────────────────────────────
 
presetMode    = input.string("Default", "Configuration Preset", group = ewmac_settings, options = ["Default", "Fast Response", "Smooth Trend"], tooltip = tooltip_preset)
srcInput      = input.source(close, "Price Source", group = ewmac_settings, tooltip = tooltip_src)
maType        = input.string("EMA", "Smoothing Algorithm (MA Engine)", group = ewmac_settings, options = ["EMA", "SMA", "WMA", "RMA", "HMA", "LSMA", "VWMA", "ALMA", "DEMA", "TEMA", "ZLSMA", "McGinley", "UltSmooth", "T3", "Jurik", "Kalman2State", "ZLEMA", "KAMA", "QASE", "Kalman", "Gaussian Fractal", "TRAMA Classic", "TRAMA Modern", "RLS2", "LaguerreF"], tooltip = tooltip_ma)
maPower       = input.float(1.0, "Adaptation Sensitivity (Power)", group = ewmac_settings, minval = 0.1, maxval = 5.0, step = 0.1, tooltip = tooltip_power)
slowMult      = input.int(4, "Slow/fast Multiplier", group = ewmac_settings, minval = 2, maxval = 10, tooltip = tooltip_slowmult)
 
r1On          = input.bool(false, "Rule 1", group = ewmac_settings, inline = "R1")
r1Len         = input.int(2, "", group = ewmac_settings, inline = "R1", minval = 1, maxval = 500)
r1W           = input.float(1.0, "", group = ewmac_settings, inline = "R1", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule1)
r2On          = input.bool(true, "Rule 2", group = ewmac_settings, inline = "R2")
r2Len         = input.int(4, "", group = ewmac_settings, inline = "R2", minval = 1, maxval = 500)
r2W           = input.float(1.0, "", group = ewmac_settings, inline = "R2", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule2)
r3On          = input.bool(true, "Rule 3", group = ewmac_settings, inline = "R3")
r3Len         = input.int(8, "", group = ewmac_settings, inline = "R3", minval = 1, maxval = 500)
r3W           = input.float(1.0, "", group = ewmac_settings, inline = "R3", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule3)
r4On          = input.bool(true, "Rule 4", group = ewmac_settings, inline = "R4")
r4Len         = input.int(16, "", group = ewmac_settings, inline = "R4", minval = 1, maxval = 500)
r4W           = input.float(1.0, "", group = ewmac_settings, inline = "R4", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule4)
r5On          = input.bool(true, "Rule 5", group = ewmac_settings, inline = "R5")
r5Len         = input.int(32, "", group = ewmac_settings, inline = "R5", minval = 1, maxval = 500)
r5W           = input.float(1.0, "", group = ewmac_settings, inline = "R5", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule5)
r6On          = input.bool(false, "Rule 6", group = ewmac_settings, inline = "R6")
r6Len         = input.int(64, "", group = ewmac_settings, inline = "R6", minval = 1, maxval = 500)
r6W           = input.float(1.0, "", group = ewmac_settings, inline = "R6", minval = 0.0, maxval = 10.0, step = 0.1, tooltip = tooltip_rule6)
 
// ───────────────────────────── Inputs: Engines ─────────────────────────────
 
adaptFloor    = input.bool(true, "α Floor by Length (KAMA / TRAMA / Fractal)", group = engine_settings, tooltip = tooltip_adaptfloor)
adaptBoost    = input.float(10.0, "QASE / TRAMA Modern: Boost", group = engine_settings, minval = 0.0, maxval = 50.0, step = 0.5, tooltip = tooltip_boost)
adaptCap      = input.float(0.8, "QASE / TRAMA Modern: α Cap", group = engine_settings, minval = 0.05, maxval = 1.0, step = 0.05, tooltip = tooltip_capalpha)
abBetaMul     = input.float(1.0, "QASE / RLS2: β Multiplier", group = engine_settings, minval = 0.0, maxval = 5.0, step = 0.1, tooltip = tooltip_betamul)
kalSens       = input.float(1.0, "Kalman: Sensitivity", group = engine_settings, minval = 0.05, maxval = 10.0, step = 0.05, tooltip = tooltip_kalsens)
kalP0         = input.float(1.0, "Kalman: Initial P0", group = engine_settings, minval = 0.0001, maxval = 100.0, step = 0.1, tooltip = tooltip_kalp0)
kamaFast      = input.int(2, "KAMA: Fast Period", group = engine_settings, minval = 1, maxval = 50, tooltip = tooltip_kamafast)
kamaSlow      = input.int(30, "KAMA: Slow Period", group = engine_settings, minval = 2, maxval = 500, tooltip = tooltip_kamaslow)
fracK         = input.float(4.6, "Fractal: K Coefficient", group = engine_settings, minval = 0.5, maxval = 20.0, step = 0.1, tooltip = tooltip_frack)
fracMinA      = input.float(0.01, "Fractal: Min α", group = engine_settings, minval = 0.001, maxval = 1.0, step = 0.005, tooltip = tooltip_fracmin)
fracMaxA      = input.float(1.0, "Fractal: Max α", group = engine_settings, minval = 0.05, maxval = 1.0, step = 0.05, tooltip = tooltip_fracmax)
fracDefD      = input.float(1.5, "Fractal: Default Dimension", group = engine_settings, minval = 1.0, maxval = 2.0, step = 0.05, tooltip = tooltip_fracd)
fracUseHL     = input.bool(true, "Fractal: Use High/Low", group = engine_settings, tooltip = tooltip_frachl)
lagPre        = input.bool(false, "Laguerre: UltimateSmoother Prefilter", group = engine_settings, tooltip = tooltip_lagpre)
lagGamma      = input.float(0.45, "Laguerre: Gamma", group = engine_settings, minval = 0.0, maxval = 0.99, step = 0.01, tooltip = tooltip_laggamma)
lagMul        = input.float(1.0, "Laguerre: Length Multiplier", group = engine_settings, minval = 0.1, maxval = 5.0, step = 0.1, tooltip = tooltip_lagmul)
 
almaOff       = input.float(0.85, "ALMA: Offset", group = engine_settings, minval = 0.0, maxval = 1.0, step = 0.05, tooltip = tooltip_almaoff)
almaSig       = input.float(6.0, "ALMA: Sigma", group = engine_settings, minval = 0.5, maxval = 20.0, step = 0.5, tooltip = tooltip_almasig)
mcgK          = input.float(0.6, "McGinley: K Coefficient", group = engine_settings, minval = 0.1, maxval = 2.0, step = 0.05, tooltip = tooltip_mcgk)
t3V           = input.float(0.7, "T3: Volume Coefficient", group = engine_settings, minval = 0.0, maxval = 1.0, step = 0.05, tooltip = tooltip_t3v)
jurPhase      = input.int(0, "Jurik: Phase", group = engine_settings, minval = -100, maxval = 100, tooltip = tooltip_jurphase)
jurPow        = input.int(2, "Jurik: Power", group = engine_settings, minval = 1, maxval = 5, tooltip = tooltip_jurpow)
k2Sens        = input.float(1.0, "Kalman2State: Sensitivity", group = engine_settings, minval = 0.05, maxval = 10.0, step = 0.05, tooltip = tooltip_k2sens)
 
// ───────────────────────────── Inputs: Volatility, Score, Signals ─────────────────────────────
 
volLenIn      = input.int(32, "Volatility Period", group = volatility_settings, minval = 5, maxval = 500, tooltip = tooltip_vol_len)
blendWeightIn = input.float(0.30, "Long-term Volatility Weight", group = volatility_settings, minval = 0.0, maxval = 1.0, step = 0.05, tooltip = tooltip_blend_weight)
blendLenIn    = input.int(500, "Long-term Volatility Period", group = volatility_settings, minval = 50, maxval = 5000, tooltip = tooltip_blend_len)
 
scoreMode     = input.string("Fast - Slow (Classic)", "Score Mode", group = score_settings, options = ["Fast - Slow (Classic)", "Fast Slope", "Price Deviation from fast"], tooltip = tooltip_scoremode)
slopeBars     = input.int(0, "Slope Window (0 = fast length)", group = score_settings, minval = 0, maxval = 500, tooltip = tooltip_slopebars)
scalingMode   = input.string("Adaptive", "Scaling Method", group = score_settings, options = ["Adaptive", "Fixed"], tooltip = tooltip_scaling_mode)
scalingLenIn  = input.int(250, "Adaptive Scaling Period", group = score_settings, minval = 20, maxval = 2000, tooltip = tooltip_scaling_len)
scaleTarget   = input.float(10.0, "Target Mean |score|", group = score_settings, minval = 1.0, maxval = 50.0, step = 0.5, tooltip = tooltip_scaletarget)
fixedScaleNum = input.float(15.0, "Fixed: Scale Numerator", group = score_settings, minval = 1.0, maxval = 100.0, step = 0.5, tooltip = tooltip_fixedscale)
multiplierIn  = input.float(0.0, "Diversification Multiplier (0 = Auto)", group = score_settings, minval = 0.0, maxval = 3.0, step = 0.01, tooltip = tooltip_multiplier)
scoreCap      = input.float(20.0, "Score Cap", group = score_settings, minval = 5.0, maxval = 100.0, step = 1.0, tooltip = tooltip_score_cap)
 
entryThIn     = input.float(4.0, "Entry Threshold", group = signal_settings, minval = 0.5, maxval = 20.0, step = 0.5, tooltip = tooltip_entry)
useNeutral    = input.bool(true, "Use Neutral State", group = signal_settings, tooltip = tooltip_neutral_state)
exitFracIn    = input.float(0.50, "Exit Fraction", group = signal_settings, minval = 0.0, maxval = 1.0, step = 0.05, tooltip = tooltip_exit_frac)
 
// ───────────────────────────── Inputs: HTF ─────────────────────────────
 
useHtf        = input.bool(false, "Enable HTF Trend Filter", group = htf_settings, tooltip = tooltip_usehtf)
htfRes        = input.timeframe("240", "Filter Timeframe (HTF)", group = htf_settings, tooltip = tooltip_htfres)
htfMaAlg      = input.string("EMA", "MA Algorithm for HTF", group = htf_settings, options = ["EMA", "SMA", "WMA", "RMA", "HMA", "LSMA", "VWMA", "ALMA", "DEMA", "TEMA", "ZLSMA", "McGinley", "UltSmooth", "T3", "Jurik", "Kalman2State", "ZLEMA", "KAMA", "QASE", "Kalman", "Gaussian Fractal", "TRAMA Classic", "TRAMA Modern", "RLS2", "LaguerreF"], tooltip = tooltip_htfalg)
htfLen        = input.int(50, "MA Period for HTF Trend", group = htf_settings, minval = 5, maxval = 500, tooltip = tooltip_htflen)
 
// ───────────────────────────── Inputs: Visualization ─────────────────────────────
 
colorPreset   = input.string("Custom", "Color Preset", group = visual_settings, options = ["Custom", "Classic", "Aqua", "Cosmic", "Cyber", "Neon"], tooltip = tooltip_color_preset)
bullCustom    = input.color(#00ffaa, "Bullish Trend Color", group = visual_settings, tooltip = tooltip_bullish)
bearCustom    = input.color(#ff0000, "Bearish Trend Color", group = visual_settings, tooltip = tooltip_bearish)
neutCustom    = input.color(#808080, "Neutral State Color", group = visual_settings, tooltip = tooltip_neutral_color)
lineWidth     = input.int(3, "Trend Line Width", group = visual_settings, minval = 1, maxval = 8, tooltip = tooltip_line_width)
showGlow      = input.bool(true, "Neon Glow Effect", group = visual_settings, tooltip = tooltip_glow)
glowW1        = input.int(20, "Glow: Outer Layer Width", group = visual_settings, minval = 1, maxval = 40, tooltip = tooltip_glow_w1)
glowW2        = input.int(10, "Glow: Inner Layer Width", group = visual_settings, minval = 1, maxval = 40, tooltip = tooltip_glow_w2)
glowT1        = input.int(88, "Glow: Outer Layer Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_glow_t1)
glowT2        = input.int(75, "Glow: Inner Layer Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_glow_t2)
showReadout   = input.bool(true, "Signal Status Label", group = visual_settings, tooltip = tooltip_readout)
readoutSize   = input.string("Normal", "Label Text Size", group = visual_settings, options = ["Tiny", "Small", "Normal", "Large"], tooltip = tooltip_readout_size)
colorBars     = input.bool(true, "Color Price Bars", group = visual_settings, tooltip = tooltip_barcolor)
barTrans      = input.int(0, "Bar Color Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_bartrans)
colorBg       = input.bool(false, "Chart Background Color", group = visual_settings, tooltip = tooltip_bgcolor)
bgTrans       = input.int(90, "Background Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_bgtrans)
 
//              ╔════════════════════════════════╗              //
//              ║      PRESET CONFIGURATION      ║              //
//              ╚════════════════════════════════╝              //
 
bool p1 = switch presetMode
    "Fast Response" => true
    "Smooth Trend" => false
    => r1On
 
bool p2 = switch presetMode
    "Fast Response" => true
    "Smooth Trend" => false
    => r2On
 
bool p3 = switch presetMode
    "Fast Response" => true
    "Smooth Trend" => false
    => r3On
 
bool p4 = switch presetMode
    "Fast Response" => true
    "Smooth Trend" => true
    => r4On
 
bool p5 = switch presetMode
    "Fast Response" => false
    "Smooth Trend" => true
    => r5On
 
bool p6 = switch presetMode
    "Fast Response" => false
    "Smooth Trend" => true
    => r6On
 
int volLen = switch presetMode
    "Fast Response" => 16
    "Smooth Trend" => 64
    => volLenIn
 
float blendWeight = switch presetMode
    "Fast Response" => 0.15
    "Smooth Trend" => 0.40
    => blendWeightIn
 
int blendLen = switch presetMode
    "Fast Response" => 250
    "Smooth Trend" => 750
    => blendLenIn
 
int scalingLen = switch presetMode
    "Fast Response" => 150
    "Smooth Trend" => 400
    => scalingLenIn
 
float entryTh = switch presetMode
    "Fast Response" => 2.5
    "Smooth Trend" => 6.0
    => entryThIn
 
float exitFrac = switch presetMode
    "Fast Response" => 0.70
    "Smooth Trend" => 0.35
    => exitFracIn
 
//              ╔════════════════════════════════╗              //
//              ║         VOLATILITY UNIT        ║              //
//              ╚════════════════════════════════╝              //
 
float srcSafe = math.max(srcInput, 0.0000000001)
float ret = math.log(srcSafe / math.max(nz(srcSafe[1], srcSafe), 0.0000000001))
 
float volShort = ta.stdev(ret, volLen)
float volLong = ta.sma(volShort, blendLen)
float volPct = not na(volLong) ? volShort * (1.0 - blendWeight) + volLong * blendWeight : volShort
volPct := math.max(volPct, 0.0000000001)
 
float volPrice = volPct * srcSafe
 
//              ╔════════════════════════════════╗              //
//              ║   ADVANCED QUANT & FRACTAL MA  ║              //
//              ╚════════════════════════════════╝              //
// Each call site has its own history, so fast/slow and rules 1-6 do not share memory.
 
// Trend efficiency (Kaufman ER): |change over len| / sum |changes per bar|
f_er(float src, int len) =>
    float chg  = math.abs(src - nz(src[len], src))
    float path = ta.sma(math.abs(src - nz(src[1], src)), len) * len
    path > 0.0 ? chg / path : 0.0
 
// Kalman (local level model). Q/R ratio is chosen so that steady-state
// gain equals α = 2/(len+1): fast is faster than slow.
f_kalman(float src, int len) =>
    float a  = 2.0 / (len + 1.0)
    float qn = kalSens * a * a / math.max(1.0 - a, 0.0001)
    float x  = na
    float p  = na
    float xPrev = nz(x[1], src)
    float pPred = nz(p[1], kalP0) + qn
    float k = pPred / (pPred + 1.0)
    x := xPrev + k * (src - xPrev)
    p := (1.0 - k) * pPred
    x
 
// Gaussian Fractal (FRAMA-like): α = exp(-K*(D-1)), D is the fractal dimension
f_frama(float s, int l) =>
    int half  = math.max(math.floor(l / 2), 2)
    int full  = half * 2
    float hiS = fracUseHL ? high : s
    float loS = fracUseHL ? low : s
    float hn1 = ta.highest(hiS, half)
    float ln1 = ta.lowest(loS, half)
    float hn2 = nz(hn1[half], hn1)
    float ln2 = nz(ln1[half], ln1)
    float hn3 = ta.highest(hiS, full)
    float ln3 = ta.lowest(loS, full)
    float n1  = (hn1 - ln1) / half
    float n2  = (hn2 - ln2) / half
    float n3  = (hn3 - ln3) / full
    float dim = n3 > 0.0 and n1 + n2 > 0.0 ? (math.log(n1 + n2) - math.log(n3)) / math.log(2.0) : fracDefD
    float aRaw = math.exp(-fracK * (dim - 1.0))
    float aLo  = adaptFloor ? math.max(2.0 / (l + 1.0), fracMinA) : fracMinA
    float a    = math.max(aLo, math.min(aRaw, fracMaxA))
    float gf   = na
    gf := nz(gf[1], s) + a * (s - nz(gf[1], s))
    gf
 
// QASE: alpha-beta filter with adaptive α by ER
f_qase(float src, int len, float power) =>
    float er   = f_er(src, len)
    float aMin = 2.0 / (len + 1.0)
    float aMax = math.max(aMin, math.min(aMin * (1.0 + adaptBoost * power), adaptCap))
    float a    = aMin + er * (aMax - aMin)
    float b    = abBetaMul * a * a / (2.0 - a)
    float pm   = na
    float vm   = na
    float pPrev = nz(pm[1], src)
    float vPrev = nz(vm[1], 0.0)
    float pPred = pPrev + vPrev
    float e     = src - pPred
    pm := pPred + a * e
    vm := vPrev + b * e
    pm
 
// RLS2: alpha-beta filter with constant α = 2/(len+1)
f_rls2(float src, int len) =>
    float a  = 2.0 / (len + 1.0)
    float b  = abBetaMul * a * a / (2.0 - a)
    float pm = na
    float vm = na
    float pPrev = nz(pm[1], src)
    float vPrev = nz(vm[1], 0.0)
    float pPred = pPrev + vPrev
    float e     = src - pPred
    pm := pPred + a * e
    vm := vPrev + b * e
    pm
 
// kama
f_kama(float src, int len) =>
    float er  = f_er(src, len)
    float aHi = 2.0 / (kamaFast + 1.0)
    float aLo = math.min(adaptFloor ? 2.0 / (len + 1.0) : 2.0 / (kamaSlow + 1.0), aHi)
    float lin = aLo + er * (aHi - aLo)
    float sc  = adaptFloor ? lin : lin * lin
    float km  = na
    km := nz(km[1], src) + sc * (src - nz(km[1], src))
    km
 
// TRAMA Classic
f_trama_classic(float src, int len, float power) =>
    float er  = f_er(src, len)
    float aLo = adaptFloor ? 2.0 / (len + 1.0) : 0.0
    float a   = math.max(aLo, math.min(math.pow(er, power), 1.0))
    float tc  = na
    tc := nz(tc[1], src) + a * (src - nz(tc[1], src))
    tc
 
// TRAMA Modern
f_trama_modern(float src, int len, float power) =>
    float er   = f_er(src, len)
    float aMin = 2.0 / (len + 1.0)
    float aMax = math.max(aMin, math.min(aMin * (1.0 + adaptBoost * power), adaptCap))
    float a    = aMin + math.pow(er, power) * (aMax - aMin)
    float tm   = na
    tm := nz(tm[1], src) + a * (src - nz(tm[1], src))
    tm
 
// Laguerre : UltimateSmoother prefilter (optional) + classic Laguerre cascade
// Filt = (L0 + 2*L1 + 2*L2 + L3) / 6 — weights converge with the divisor, gain = 1
f_laguerre(float src, int len) =>
    float per = math.max(len * lagMul, 1.0)
    float a1  = math.exp(-1.414 * math.pi / per)
    float c2  = 2.0 * a1 * math.cos(1.414 * math.pi / per)
    float c3  = -a1 * a1
    float c1  = (1.0 + c2 - c3) / 4.0
    float us  = na
    us := (1.0 - c1) * src + (2.0 * c1 - c2) * nz(src[1], src) - (c1 + c3) * nz(src[2], src) + c2 * nz(us[1], src) + c3 * nz(us[2], src)
    float inp = lagPre ? us : src
    float g   = lagPre ? lagGamma : math.max(0.0, math.min(1.0 - 2.0 / (len * lagMul + 1.0), 0.99))
    float L0  = na
    float L1  = na
    float L2  = na
    float L3  = na
    float q0  = nz(L0[1], inp)
    float q1  = nz(L1[1], inp)
    float q2  = nz(L2[1], inp)
    float q3  = nz(L3[1], inp)
    L0 := (1.0 - g) * inp + g * q0
    L1 := -g * L0 + q0 + g * q1
    L2 := -g * L1 + q1 + g * q2
    L3 := -g * L2 + q2 + g * q3
    (L0 + 2.0 * L1 + 2.0 * L2 + L3) / 6.0
 
// DEMA / TEMA / ZLSMA — low lag (for 'Fast Slope' score mode and HTF)
f_dema(float src, int len) =>
    float e1 = ta.ema(src, len)
    2.0 * e1 - ta.ema(e1, len)
 
f_tema(float src, int len) =>
    float e1 = ta.ema(src, len)
    float e2 = ta.ema(e1, len)
    3.0 * (e1 - e2) + ta.ema(e2, len)
 
f_zlsma(float src, int len) =>
    float lr = ta.linreg(src, len, 0)
    lr + (lr - ta.linreg(lr, len, 0))
 
// McGinley Dynamic (denominator floored at 1 to prevent overshoot)
f_mcginley(float src, int len) =>
    float md    = na
    float prev  = nz(md[1], src)
    float ratio = prev != 0.0 ? src / prev : 1.0
    md := prev + (src - prev) / math.max(mcgK * len * math.pow(ratio, 4), 1.0)
    md
 
// UltimateSmoother (Ehlers): flat passband
f_ultsmooth(float src, int len) =>
    float per = math.max(len * 1.0, 1.0)
    float a1  = math.exp(-1.414 * math.pi / per)
    float c2  = 2.0 * a1 * math.cos(1.414 * math.pi / per)
    float c3  = -a1 * a1
    float c1  = (1.0 + c2 - c3) / 4.0
    float us  = na
    us := (1.0 - c1) * src + (2.0 * c1 - c2) * nz(src[1], src) - (c1 + c3) * nz(src[2], src) + c2 * nz(us[1], src) + c3 * nz(us[2], src)
    us
// T3 (Tillson)
f_t3(float src, int len) =>
    float e1 = ta.ema(src, len)
    float e2 = ta.ema(e1, len)
    float e3 = ta.ema(e2, len)
    float e4 = ta.ema(e3, len)
    float e5 = ta.ema(e4, len)
    float e6 = ta.ema(e5, len)
    float b  = t3V
    float c1 = -b * b * b
    float c2 = 3.0 * b * b + 3.0 * b * b * b
    float c3 = -6.0 * b * b - 3.0 * b - 3.0 * b * b * b
    float c4 = 1.0 + 3.0 * b + b * b * b + 3.0 * b * b
    c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3
 
// Jurik
f_jurik(float src, int len) =>
    float phr = jurPhase < -100 ? 0.5 : jurPhase > 100 ? 2.5 : jurPhase / 100.0 + 1.5
    float b   = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
    float a   = math.pow(b, jurPow)
    float e0  = na
    float e1  = na
    float e2  = na
    float jv  = na
    float jPrev = nz(jv[1], src)
    e0 := (1.0 - a) * src + a * nz(e0[1], src)
    e1 := (src - e0) * (1.0 - b) + b * nz(e1[1], 0.0)
    e2 := (e0 + phr * e1 - jPrev) * math.pow(1.0 - a, 2) + math.pow(a, 2) * nz(e2[1], 0.0)
    jv := e2 + jPrev
    jv
// Kalman2State: state = [level, velocity], measurement noise R = 1.
 
f_kalman2(float src, int len) =>
    float a   = 2.0 / (len + 1.0)
    float qn  = k2Sens * 0.869 * math.pow(a, 4.35)
    float lev = na
    float vel = na
    float c11 = na
    float c12 = na
    float c21 = na
    float c22 = na
    float lPrev = nz(lev[1], src)
    float vPrev = nz(vel[1], 0.0)
    float q11 = nz(c11[1], 1.0)
    float q12 = nz(c12[1], 0.0)
    float q21 = nz(c21[1], 0.0)
    float q22 = nz(c22[1], 1.0)
    float predLevel = lPrev + vPrev
    float p11p = q11 + q12 + q21 + q22 + qn
    float p12p = q12 + q22
    float p21p = q21 + q22
    float p22p = q22 + qn
    float sInn = p11p + 1.0
    float k1   = p11p / sInn
    float k2   = p21p / sInn
    float innov = src - predLevel
    lev := predLevel + k1 * innov
    vel := vPrev + k2 * innov
    c11 := (1.0 - k1) * p11p
    c12 := (1.0 - k1) * p12p
    c21 := p21p - k2 * p11p
    c22 := p22p - k2 * p12p
    lev
f_ma_engine(float src, int len, string alg, float power) =>
    switch alg
        "ZLEMA" =>
            int lag = math.floor((len - 1) / 2)
            ta.ema(src + (src - nz(src[lag], src)), len)
        "SMA"              => ta.sma(src, len)
        "WMA"              => ta.wma(src, len)
        "RMA"              => ta.rma(src, len)
        "HMA"              => ta.hma(src, len)
        "LSMA"             => ta.linreg(src, len, 0)
        "VWMA"             => ta.vwma(src, len)
        "ALMA"             => ta.alma(src, len, almaOff, almaSig)
        "DEMA"             => f_dema(src, len)
        "TEMA"             => f_tema(src, len)
        "ZLSMA"            => f_zlsma(src, len)
        "McGinley"         => f_mcginley(src, len)
        "UltSmooth"        => f_ultsmooth(src, len)
        "T3"               => f_t3(src, len)
        "Jurik"            => f_jurik(src, len)
        "Kalman2State"     => f_kalman2(src, len)
        "KAMA"             => f_kama(src, len)
        "QASE"             => f_qase(src, len, power)
        "Kalman"           => f_kalman(src, len)
        "Gaussian Fractal" => f_frama(src, len)
        "TRAMA Classic"    => f_trama_classic(src, len, power)
        "TRAMA Modern"     => f_trama_modern(src, len, power)
        "RLS2"             => f_rls2(src, len)
        "LaguerreF"        => f_laguerre(src, len)
        => ta.ema(src, len)
 
//              ╔════════════════════════════════╗              //
//              ║          EWMAC ENGINE          ║              //
//              ╚════════════════════════════════╝              //
 
ewmacRule(float src, simple int fastLen, float riskUnit, simple int scaleLen, bool adaptive, float cap, string alg, float pwr) =>
    float fastMa = f_ma_engine(src, fastLen, alg, pwr)
    float slowMa = f_ma_engine(src, fastLen * slowMult, alg, pwr)
    int sk = slopeBars > 0 ? slopeBars : fastLen
    float rawSel = scoreMode == "Fast Slope" ? fastMa - nz(fastMa[sk], fastMa) : scoreMode == "Price Deviation from fast" ? src - fastMa : fastMa - slowMa
    float raw = rawSel / math.max(riskUnit, 0.0000000001)
    float avgAbs = ta.sma(math.abs(raw), scaleLen)
    float fixedScale = fixedScaleNum / math.sqrt(fastLen)
    float scaleFactor = adaptive and not na(avgAbs) ? scaleTarget / math.max(avgAbs, 0.0000000001) : fixedScale
    float score = math.max(math.min(raw * scaleFactor, cap), -cap)
    float midpoint = (fastMa + slowMa) / 2.0
    [score, midpoint]
 
bool adaptiveScaling = scalingMode == "Adaptive"
 
[score1, mid1] = ewmacRule(srcSafe, r1Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
[score2, mid2] = ewmacRule(srcSafe, r2Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
[score3, mid3] = ewmacRule(srcSafe, r3Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
[score4, mid4] = ewmacRule(srcSafe, r4Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
[score5, mid5] = ewmacRule(srcSafe, r5Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
[score6, mid6] = ewmacRule(srcSafe, r6Len, volPrice, scalingLen, adaptiveScaling, scoreCap, maType, maPower)
 
float weightSum = 0.0
float scoreSum = 0.0
float lineSum = 0.0
int activeCount = 0
 
if p1 and r1W > 0.0
    weightSum += r1W
    scoreSum += score1 * r1W
    lineSum += mid1 * r1W
    activeCount += 1
if p2 and r2W > 0.0
    weightSum += r2W
    scoreSum += score2 * r2W
    lineSum += mid2 * r2W
    activeCount += 1
if p3 and r3W > 0.0
    weightSum += r3W
    scoreSum += score3 * r3W
    lineSum += mid3 * r3W
    activeCount += 1
if p4 and r4W > 0.0
    weightSum += r4W
    scoreSum += score4 * r4W
    lineSum += mid4 * r4W
    activeCount += 1
if p5 and r5W > 0.0
    weightSum += r5W
    scoreSum += score5 * r5W
    lineSum += mid5 * r5W
    activeCount += 1
if p6 and r6W > 0.0
    weightSum += r6W
    scoreSum += score6 * r6W
    lineSum += mid6 * r6W
    activeCount += 1
 
float multiplierTable = switch activeCount
    0 => 1.00
    1 => 1.00
    2 => 1.10
    3 => 1.20
    4 => 1.27
    5 => 1.32
    => 1.36
 
float divMultiplier = multiplierIn > 0.0 ? multiplierIn : multiplierTable
float trendScoreRaw = weightSum > 0.0 ? scoreSum / weightSum * divMultiplier : 0.0
float trendScore = math.max(math.min(trendScoreRaw, scoreCap), -scoreCap)
float trendLine = weightSum > 0.0 ? lineSum / weightSum : srcSafe
 
//              ╔════════════════════════════════╗              //
//              ║          SIGNAL ENGINE         ║              //
//              ╚════════════════════════════════╝              //
 
float exitTh = entryTh * exitFrac
 
// HTF filter without repaint: take values of the LAST CLOSED HTF bar ([1] + lookahead_on).
// The filter works only if HTF is strictly higher than the current timeframe.
bool htfValid = timeframe.in_seconds(htfRes) > timeframe.in_seconds(timeframe.period)
bool htfOn    = useHtf and htfValid
 
[htfC, htfV] = request.security(syminfo.tickerid, htfRes, [close[1], f_ma_engine(close, htfLen, htfMaAlg, maPower)[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
 
bool htfBull = htfC > htfV
bool htfBear = htfC < htfV
 
var int signalState = 0
 
if barstate.isconfirmed
    bool allowBull = not htfOn or htfBull
    bool allowBear = not htfOn or htfBear
 
    if trendScore > entryTh and signalState != 1 and allowBull
        signalState := 1
    else if trendScore < -entryTh and signalState != -1 and allowBear
        signalState := -1
    else if useNeutral and signalState == 1 and trendScore < exitTh
        signalState := 0
    else if useNeutral and signalState == -1 and trendScore > -exitTh
        signalState := 0
 
bool turnedBull = signalState == 1 and signalState[1] != 1
bool turnedBear = signalState == -1 and signalState[1] != -1
bool turnedNeut = signalState == 0 and signalState[1] != 0
bool signalChanged = turnedBull or turnedBear or turnedNeut
 
//              ╔════════════════════════════════╗              //
//              ║          VISUALIZATION         ║              //
//              ╚════════════════════════════════╝              //
 
color bullCol = switch colorPreset
    "Classic" => #00ff00
    "Aqua"    => #00d4ff
    "Cosmic"  => #49ffce
    "Cyber"   => #00cccc
    "Neon"    => #ffff00
    => bullCustom
 
color bearCol = switch colorPreset
    "Classic" => #ff0000
    "Aqua"    => #ff8c00
    "Cosmic"  => #9932cc
    "Cyber"   => #ff6600
    "Neon"    => #ff00ff
    => bearCustom
 
color neutCol = colorPreset == "Custom" ? neutCustom : #808080
 
color signalColor = signalState == 1 ? bullCol : signalState == -1 ? bearCol : neutCol
 
// The line is drawn only on confirmed bars — no repaint of the last bar
var float lineConf = na
if barstate.isconfirmed
    lineConf := trendLine
float displayLine = barstate.isconfirmed ? trendLine : na
 
plot(showGlow ? displayLine : na, "Trend Line Glow Outer", color.new(signalColor, glowT1), glowW1)
plot(showGlow ? displayLine : na, "Trend Line Glow Inner", color.new(signalColor, glowT2), glowW2)
plot(displayLine, "Trend Line", color.new(signalColor, 0), lineWidth)
 
// Score value — only in Data Window / status line (for tuning the entry threshold)
plot(barstate.isconfirmed ? trendScore : na, "Trend Score", color.new(signalColor, 0), display = display.data_window + display.status_line)
 
barcolor(colorBars ? color.new(signalColor, barTrans) : na, title = "Trend Bar Color")
bgcolor(colorBg ? color.new(signalColor, bgTrans) : na, title = "Trend Background Color")
 
string readoutTextSize = switch readoutSize
    "Tiny" => size.tiny
    "Small" => size.small
    "Large" => size.large
    => size.normal
 
readoutTextColor(color fillColor) =>
    float brightness = (color.r(fillColor) * 299.0 + color.g(fillColor) * 587.0 + color.b(fillColor) * 114.0) / 1000.0
    brightness >= 128.0 ? color.black : color.white
 
var label signalReadout = na
 
if showReadout and barstate.islast and not na(lineConf)
    label.delete(signalReadout)
    int lblBar = barstate.isconfirmed ? bar_index : bar_index - 1
    string readoutText = signalState == 1 ? "  Bullish  " : signalState == -1 ? "  Bearish  " : "  Neutral  "
    color readoutFill = color.new(signalColor, 0)
    signalReadout := label.new(lblBar, lineConf, readoutText, xloc = xloc.bar_index, style = label.style_label_left, color = readoutFill, textcolor = readoutTextColor(readoutFill), size = readoutTextSize)
 
//              ╔════════════════════════════════╗              //
//              ║             ALERTS             ║              //
//              ╚════════════════════════════════╝              //
 
alertcondition(turnedBull, title = "Bullish Trend Signal", message = "Trend Signals: BULLISH trend confirmed on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(turnedBear, title = "Bearish Trend Signal", message = "Trend Signals: BEARISH trend confirmed on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(turnedNeut, title = "Neutral Trend Signal", message = "Trend Signals: Trend released to NEUTRAL on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(signalChanged, title = "Trend Signal Changed", message = "Trend Signals: Trend signal changed on {{exchange}}:{{ticker}} - {{interval}}")

← 返回列表