← К каталогу
Исходный код · ID 4120

Artemis Squeeze Momentum

indicator artemis squeeze momentum for tradingview.pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Artemis Squeeze Momentum — индикатор анализа моментума для TradingView, объединяющий несколько аналитических слоёв в одном осцилляторном окне. Он рассчитывает линейную регрессию моментума относительно канальной середины с нормализацией по волатильности, строит направленный поток на основе соотношения восходящих и нисходящих движений, а также определяет трёхуровневое сжатие канала по соотношению стандартного отклонения и среднеквадратичного отклонения. Индикатор предоставляет визуальные маркеры разжатия, предсказание направления при выходе из сжатия, стрелки совпадения моментума и потока, детекцию обычных и скрытых расхождений с умным фильтром, составную оценку силы тренда, определение режима рынка по ADX, панель мультитаймфреймового совпадения и настраиваемую информационную панель с темами оформления.

Настройки программы

НастройкаОписание
themeChoice Тема оформления — Выбирает цветовую палитру из тринадцати вариантов, которая определяет цвета линии моментума, заливок потока, индикаторов совпадения, линий расхождений и всей панели.
showMom Показать моментум — Включает или скрывает основную линию моментума и заливку между линией и сигнальной линией.
fluxHA Использовать бары Хайкин Аси — При включении потоковый осциллятор рассчитывается на барах Хайкин Аси вместо обычных OHLC, что сглаживает шум и подчёркивает направление тренда.
showFlux Показать поток — Включает или скрывает область заливки направленного потока. Даже при скрытии поток продолжает влиять на индикаторы совпадения.
showSqz Показать сжатие — Включает отображение столбца сжатия на нулевой линии, цвет которого зависит от степени компрессии канала.
showSqzRelease Показать разжатие — Отображает маркер ✦ на баре, где сжатие полностью завершается, сигнализируя о начале расширения волатильности.
sqzPredictOn Показать предсказание направления — При включении маркер разжатия становится направленным: ✦▴ для бычьего, ✦▾ для медвежьего наклона моментума в момент выхода из сжатия.
sqzPredictLook Глубина предсказания — Количество баров назад, по которым измеряется наклон моментума в точке разжатия для определения направления.
sqzPredictThresh Порог наклона предсказания — Минимальная абсолютная величина наклона, необходимая для отображения направленной стрелки. Ниже порога маркер остаётся нейтральным ✦.
gaugeMode Режим отображения индикаторов совпадения — Выбирает, какие полосы совпадения отображать: обе, только бычью, только медвежью или ни одной.
confThresh Порог сигнала — Минимальная абсолютная величина моментума, при которой стрелки совпадения могут сработать. Чем выше порог, тем меньше, но более уверенных сигналов.
volConfOn Подтверждение объёмом — При включении стрелки совпадения появляются только при превышении текущего объёма его скользящей средней, фильтруя слабые сигналы.
volMaLen Длина MA объёма — Период скользящей средней объёма, используемой как порог для подтверждения объёмом.
divSens Чувствительность расхождений — Минимальная абсолютная величина моментума, при которой кроссовер становится кандидатом на расхождение.
divRegOn Обычные расхождения — Включает детекцию обычных расхождений, сигнализирующих о потенциальном развороте тренда.
divHidOn Скрытые расхождения — Включает детекцию скрытых расхождений, сигнализирующих о продолжении текущего тренда.
divShowLines Показать линии расхождений — Включает или скрывает соединительные линии между точками расхождений.
divShowLabels Показать метки расхождений — Включает или скрывает маркеры D▲ D▼ H▲ H▼ на графике.
divLabelSize Размер меток расхождений — Размер текста маркеров расхождений: Tiny, Small, Normal или Large.
sdfOn Умный фильтр расхождений — Включает дополнительную фильтрацию расхождений по трём критериям: минимальный размах моментума, минимальный размах цены и подтверждение потоком.
sdfMinMom Минимальный размах моментума — Минимальная разница между значениями моментума на двух точках расхождения, ниже которой сигнал отклоняется.
sdfMinPct Минимальный размах цены (%) — Минимальное процентное движение цены между точками расхождения относительно недавнего диапазона.
sdfFluxConf Подтверждение потоком — При включении направление потока должно совпадать с направлением расхождения для его прохождения фильтра.
regimeOn Показать режим рынка — Включает детектор режима рынка на основе ADX, отображающий текущие состояние: тренд вверх, тренд вниз, боковик или переход.
regimeLen Длина ADX — Период расчёта ADX для определения режима рынка.
regimeTrendTh Порог тренда — Значение ADX выше которого рынок классифицируется как трендовый.
regimeRangeTh Порог боковика — Значение ADX ниже которого рынок классифицируется как боковик.
regimeAdaptive Автоподстройка порога сигнала — При включении порог сигнала совпадения автоматически сдвигается в зависимости от текущего режима рынка.
barMode Режим окраски свечей — Выбирает режим окраски всех свечей на графике по состоянию моментума, потока, сжатия, совпадения или наклона.
showMTF Показать мультитаймфреймовую панель — Включает панель, показывающую совпадение направлений на четырёх более высоких таймфреймах одновременно.
mtfPreset Пресет таймфреймов — Выбирает предустановленный набор из четырёх таймфреймов для мультитаймфреймовой панели.
mtfPos Позиция панели таймфреймов — Определяет место размещения мультитаймфреймовой панели внутри окна индикатора.
mtfSize Размер текста панели таймфреймов — Размер текста в мультитаймфреймовой панели.
showDash Показать панель данных — Включает информационную панель с текущими значениями: смещение, оценка силы тренда, режим, моментум, поток, сжатие, совпадение, последнее расхождение и наклон.
dashPos Позиция панели данных — Определяет место размещения информационной панели внутри окна индикатора.
dashSize Размер текста панели данных — Размер текста в информационной панели.
Получить полный код

Поиск по коду файла

indicator("Artemis Squeeze Momentum", shorttitle = "Artemis SM", overlay = false, precision = 2, max_lines_count = 500, max_labels_count = 500, explicit_plot_zorder = true)

type Bar
    float o
    float h
    float l
    float c

type MomReading
    float value
    float signal

type FluxReading
    float value
    float overflow

type SqueezeState
    bool tight
    bool mid
    bool loose

string GRP_THEME = "Visual 🔹"
string GRP_MOM   = "Momentum Core 🔹"
string GRP_FLUX  = "Directional Flux 🔹"
string GRP_SQZ   = "Squeeze Engine 🔹"
string GRP_GAUGE = "Confluence Gauges 🔹"
string GRP_DIV    = "Divergence 🔹"
string GRP_REGIME = "Trend Regime 🔹"
string GRP_BAR    = "Bar Coloring 🔹"
string GRP_MTF    = "Multi-Timeframe 🔹"
string GRP_DASH   = "Dashboard 🔹"
string GRP_ALRT   = "Alerts 🔹"

themeChoice = input.string("Tropic", "Theme",
     options = ["Tropic", "Amber", "Pastel", "Cyber", "Helios", "Electric", "Candy", "Bloomberg", "Solar", "Royal", "Emerald", "Midnight", "Graphite"],
     group   = GRP_THEME,
     tooltip = "Applies a complete color palette across all Artemis Squeeze components.\nOne selection governs the Momentum line, Flux fills, Confluence gauges, Divergence lines and Dashboard.\n\nTropic — Cyan steel + deep orange (electric contrast — default)\n\nAmber — Warm amber + ember red (fire tones)\n\nPastel — Sky blue + soft lavender (cool arctic glow)\n\nCyber — Neon lime + hot crimson (cyber terminal)\n\nHelios — Bright gold + scarlet (solar warmth)\n\nElectric — Electric aqua + magenta (high-voltage neon)\n\nCandy — Neon green + hot pink (dark energy pop)\n\nBloomberg — Terminal orange + cyan (Wall Street finance heritage — PRO)\n\nSolar — Solarized olive + crimson (developer palette, easy on the eyes — PRO)\n\nRoyal — Imperial gold + deep purple (luxury signature — PRO)\n\nEmerald — Vibrant emerald + ruby red (jewel-tone finance — PRO)\n\nMidnight — Deep navy + dark crimson (dark depth)\n\nGraphite — Near-black + silver grey (monochrome minimal)")

color thBull = switch themeChoice
    "Tropic"    => #00bcd4
    "Amber"     => #ff9800
    "Pastel"    => #4fc3f7
    "Cyber"     => #00e676
    "Helios"    => #ffd600
    "Electric"  => #00e5ff
    "Candy"     => #69F0AE
    "Bloomberg" => #ff8c00
    "Solar"     => #859900
    "Royal"     => #ffd700
    "Emerald"   => #00bfa5
    "Midnight"  => #0d47a1
    "Graphite"  => #1a1a1a
    =>             #00bcd4

color thBear = switch themeChoice
    "Tropic"    => #ff6d00
    "Amber"     => #e53935
    "Pastel"    => #9575cd
    "Cyber"     => #ff1744
    "Helios"    => #ef5350
    "Electric"  => #e040fb
    "Candy"     => #FF4081
    "Bloomberg" => #00b0ff
    "Solar"     => #dc322f
    "Royal"     => #6a0dad
    "Emerald"   => #c62828
    "Midnight"  => #b71c1c
    "Graphite"  => #757575
    =>             #ff6d00

color thNeutral = switch themeChoice
    "Tropic"    => #607d8b
    "Amber"     => #7986cb
    "Pastel"    => #b0bec5
    "Cyber"     => #757575
    "Helios"    => #9e9e9e
    "Electric"  => #546e7a
    "Candy"     => #455A64
    "Bloomberg" => #5a5a5a
    "Solar"     => #586e75
    "Royal"     => #4a4458
    "Emerald"   => #546e7a
    "Midnight"  => #546e7a
    "Graphite"  => #9e9e9e
    =>             #607d8b

color thSignal = switch themeChoice
    "Tropic"    => #80DEEA
    "Amber"     => #FFCC80
    "Pastel"    => #B3E5FC
    "Cyber"     => #B9F6CA
    "Helios"    => #FFF59D
    "Electric"  => #84FFFF
    "Candy"     => #CCFF90
    "Bloomberg" => #FFD180
    "Solar"     => #B5CB00
    "Royal"     => #FFE680
    "Emerald"   => #80CBC4
    "Midnight"  => #90CAF9
    "Graphite"  => #BDBDBD
    =>             #80DEEA

color sqzColTight = switch themeChoice
    "Tropic"    => #ff1100
    "Amber"     => #8b0000
    "Pastel"    => #ab47bc
    "Cyber"     => #f50057
    "Helios"    => #e65100
    "Electric"  => #aa00ff
    "Candy"     => #c51162
    "Bloomberg" => #ff1100
    "Solar"     => #cb4b16
    "Royal"     => #311b92
    "Emerald"   => #ff6f00
    "Midnight"  => #1565c0
    "Graphite"  => #cccccc
    =>             #ff1100

color sqzColMid = switch themeChoice
    "Tropic"    => #ff5e00
    "Amber"     => #d84315
    "Pastel"    => #ce93d8
    "Cyber"     => #ff4081
    "Helios"    => #f57c00
    "Electric"  => #d500f9
    "Candy"     => #e91e63
    "Bloomberg" => #ff5e00
    "Solar"     => #b58900
    "Royal"     => #4527a0
    "Emerald"   => #ffa000
    "Midnight"  => #1e88e5
    "Graphite"  => #888888
    =>             #ff5e00

color sqzColLoose = switch themeChoice
    "Tropic"    => #ffa600
    "Amber"     => #ff6f00
    "Pastel"    => #e1bee7
    "Cyber"     => #ff80ab
    "Helios"    => #ffb300
    "Electric"  => #ea80fc
    "Candy"     => #f06292
    "Bloomberg" => #ffa600
    "Solar"     => #93a1a1
    "Royal"     => #7e57c2
    "Emerald"   => #ffd54f
    "Midnight"  => #64b5f6
    "Graphite"  => #555555
    =>             #ffa600

color sqzColRelease = switch themeChoice
    "Tropic"    => #ff9500
    "Amber"     => #ff5252
    "Pastel"    => #e040fb
    "Cyber"     => #ff1744
    "Helios"    => #ff9100
    "Electric"  => #d500f9
    "Candy"     => #ff4081
    "Bloomberg" => #ff8400
    "Solar"     => #ff6f00
    "Royal"     => #b388ff
    "Emerald"   => #ffea00
    "Midnight"  => #448aff
    "Graphite"  => #1a1a1a
    =>             #ffea00

simple int momLen = input.int(20, "Length",
     minval = 7, maxval = 50, step = 1,
     group   = GRP_MOM,
     tooltip = "Lookback for the Squeeze Momentum engine and the Squeeze Detection window. Both share this length so compression and momentum stay aligned.\n\n7–14 → scalping / intraday\n20 → balanced — default\n21–30 → swing trading\n30–50 → position / weekly\n\nDefault: 20")

simple int momSigLen = input.int(3, "Signal Length",
     minval = 2, maxval = 7, step = 1,
     group   = GRP_MOM,
     tooltip = "SMA smoothing applied to the momentum line to produce the trigger line. Shorter than the Length so the two cross cleanly.\n\n2 → fast triggers, more crosses\n3 → balanced — default\n5–7 → fewer, more reliable crosses\n\nDefault: 3")

showMom = input.bool(true, "Show Momentum",
     group   = GRP_MOM,
     tooltip = "Toggle for the main momentum oscillator line + signal-line fill ribbon. Turning OFF hides the line but does not disable downstream features (squeeze, divergence, confluence) that depend on momentum state.")

simple int fluxLen = input.int(30, "Length",
     minval = 7, maxval = 50, step = 1,
     group   = GRP_FLUX,
     tooltip = "Lookback for the Directional Flux engine. Larger than the Momentum length by default so flux acts as the slower trend bias against the faster momentum oscillator.\n\n7–14 → reactive, more whipsaws\n30 → balanced — default\n40–50 → very smooth, only macro regimes register\n\nDefault: 30")

fluxHA = input.bool(false, "Use Heiken Ashi Bias",
     group   = GRP_FLUX,
     tooltip = "When ON, the Flux engine reads Heiken Ashi bars instead of raw OHLC. HA bars smooth body / wick noise and emphasise trend continuation. Best on lower timeframes where raw OHLC is noisy.\n\nDefault: OFF")

showFlux = input.bool(true, "Show Flux",
     group   = GRP_FLUX,
     tooltip = "Toggle for the Directional Flux area fills (main + overflow). Flux feeds the Confluence Gauges even when its fills are hidden.")

showSqz = input.bool(true, "Show Squeeze",
     group   = GRP_SQZ,
     tooltip = "Toggle for the zero-line squeeze column. The column lights up whenever stdev < ATR × 1.0 (any tier active); the colour escalates as compression tightens:\n\nLightest (Loose) → stdev < ATR × 1.0\nMid intensity (Mid) → stdev < ATR × 0.75\nDeepest / most saturated (Tight) → stdev < ATR × 0.5 — imminent expansion\n\nEach theme defines its OWN three-step ramp drawn from its palette family, so the squeeze column harmonises with the active theme rather than imposing a generic warning hue. The intensity semantic is preserved across every palette — tight is always the most attention-grabbing tier.")

showSqzRelease = input.bool(true, "Show Squeeze Release",
     group   = GRP_SQZ,
     tooltip = "Renders a ✦ release marker on the bar where the squeeze fully ends — when the loosest active tier (stdev < ATR × 1.0) drops off. This is the canonical \"spring uncoiled\" moment: compression ended, volatility expansion begins. Historically the highest-conviction breakout setup.\n\nMarker colour uses the theme's vivid release accent (sqzColRelease — one step brighter / more saturated than sqzColTight) so the climax moment pops visually while staying inside the theme's colour family. Hover the marker for full context.\n\nDefault: ON.")

sqzPredictOn = input.bool(true, "Show Direction Predictor",
     group   = GRP_SQZ,
     tooltip = "When ON, the ✦ Release marker becomes direction-aware: at the moment of release the engine measures momentum slope across the predictor lookback. If the slope is decisively bullish or bearish, the marker shows ✦▴ or ✦▾ instead of plain ✦.\n\nGives traders immediate breakout-direction guidance the moment compression ends — no waiting for confirmation candles. Slope within the threshold band keeps the marker neutral ✦ (\"direction unclear, wait\").\n\nDefault: ON.")

sqzPredictLook = input.int(3, "Predictor Lookback",
     minval = 2, maxval = 10, step = 1,
     group   = GRP_SQZ,
     tooltip = "How many bars back to measure momentum slope at the release bar. Shorter = more reactive but noisier; longer = smoother but slower direction reads.\n\n2 → very reactive\n3 → balanced — default\n5–10 → smooth, fewer false direction tags\n\nRequires Show Direction Predictor ON.")

sqzPredictThresh = input.float(5.0, "Predictor Slope Threshold",
     minval = 1.0, maxval = 25.0, step = 0.5,
     group   = GRP_SQZ,
     tooltip = "Minimum |slope| required to label a directional prediction. Below this absolute value the marker stays plain ✦ (neutral — \"direction unclear, wait for confirmation\").\n\n2–4 → permissive, most releases get a direction tag\n5 → balanced — default\n10+ → strict, only high-conviction directional releases earn a tag\n\nRequires Show Direction Predictor ON.")

gaugeMode = input.string("Both", "Display Mode",
     options = ["Both", "Bull", "Bear", "None"],
     group   = GRP_GAUGE,
     tooltip = "Controls which confluence strips render:\n\nBoth → both bull (top) + bear (bottom) gauges — default\nBull → bull strip only\nBear → bear strip only\nNone → disable all gauge strips\n\nConfluence states:\n• Strong Bull — mom > 0 AND flux > 0 (both bullish)\n• Weak Bull — mom > 0 OR flux > 0 (one bullish)\n• Strong Bear — mom < 0 AND flux < 0 (both bearish)\n• Weak Bear — mom < 0 OR flux < 0 (one bearish)\n\nThe strip's brightness reflects the confluence tier (full opacity for Strong, half for Weak).")

confThresh = input.int(40, "Signal Threshold",
     minval = 10, maxval = 80, step = 1,
     group   = GRP_GAUGE,
     tooltip = "Minimum |momentum| value required for a Confluence Buy ▲ or Sell ▼ arrow to fire.\n\nThe higher the value, the deeper into the overbought / oversold zone the momentum cross must happen, so fewer but higher-conviction arrows print.\n\nA Confluence arrow needs:\n• Mom × Signal crossover\n• |mom| ≥ this threshold\n• Flux opposite direction (mean-reversion bias)\n• Volume above its MA — only when Require Volume Confirmation is ON (default) and the symbol has volume data\n\n20–30 → permissive, many arrows\n40 → balanced — default\n50–80 → strict, only extreme-zone arrows\n\nNote: this is independent of the Divergence Sensitivity setting in the Divergence group. When Trend Regime → Auto-Adjust Signal Threshold is ON, this value is shifted ±10 based on detected market regime.")

volConfOn = input.bool(true, "Require Volume Confirmation",
     group   = GRP_GAUGE,
     tooltip = "When ON, Confluence Buy ▲ / Sell ▼ arrows fire only when current bar volume exceeds its moving average. Filters out signals firing during low-conviction (low-volume) periods where moves often reverse.\n\nOn symbols without volume data the gate is automatically bypassed — if either current volume or the volume MA is na or zero, the filter is skipped so the indicator remains universal.\n\nDefault: ON.")

volMaLen = input.int(20, "Volume MA Length",
     minval = 5, maxval = 100, step = 1,
     group   = GRP_GAUGE,
     tooltip = "SMA lookback for the volume threshold used by the Volume Confirmation gate.\n\n10–14 → fast (more signals pass)\n20 → balanced — default\n30–50 → slow (only high-conviction volume surges pass)\n\nRequires Require Volume Confirmation ON.")

divSens = input.int(25, "Sensitivity",
     minval = 10, maxval = 50, step = 1,
     group   = GRP_DIV,
     tooltip = "Minimum |momentum| value required for divergence detection to arm. Only momentum crossovers that happen beyond ±Sensitivity become divergence candidates.\n\n10–20 → permissive, many divergences\n25 → balanced — default\n30–50 → strict, only deep-extreme divergences\n\nHigher value = stricter filter, fewer signals, higher conviction.")

divRegOn = input.bool(true, "Regular Divergence",
     group   = GRP_DIV,
     tooltip = "Detects potential trend reversals.\n\nBull (D▲): price Lower Low + momentum Higher Low → reversal up\nBear (D▼): price Higher High + momentum Lower High → reversal down\n\nDetected at the moment of a momentum cross while in an extreme zone (|mom| > Sensitivity). Solid lines connect the divergence pivots.")

divHidOn = input.bool(true, "Hidden Divergence",
     group   = GRP_DIV,
     tooltip = "Detects trend-continuation signals.\n\nBull (H▲): price Higher Low + momentum Lower Low → uptrend continues\nBear (H▼): price Lower High + momentum Higher High → downtrend continues\n\nHidden divergences are tracked through a dedicated any-zone anchor pair (separate from the Sensitivity-gated Regular anchors), so they actually fire during shallow pullbacks within an established trend — exactly the context where the classical Hidden div pattern is supposed to appear. Dashed lines connect the two pivots.")

divShowLines = input.bool(true, "Show Divergence Lines",
     group   = GRP_DIV,
     tooltip = "Toggle for the divergence connection lines (solid for Regular, dashed for Hidden). Turning OFF keeps the labels but removes the connecting lines for a cleaner pane.")

divShowLabels = input.bool(true, "Show Divergence Labels",
     group   = GRP_DIV,
     tooltip = "Toggle for the D▲ D▼ H▲ H▼ markers. Turning OFF keeps the lines but removes the labels — useful on dense charts where labels clutter.")

divLabelSize = input.string("Tiny", "Label Size",
     options = ["Tiny", "Small", "Normal", "Large"],
     group   = GRP_DIV,
     tooltip = "Size of the D▲ D▼ H▲ H▼ divergence markers.\n\nTiny → minimal, default\nSmall → slightly larger\nNormal → standard\nLarge → maximum visibility")

sdfOn = input.bool(false, "Smart Divergence Filter (AI)",
     group   = GRP_DIV,
     tooltip = "AI-assisted filter that suppresses weak or low-quality divergences.\n\nOFF (default) → all detected divergences pass through\nON → only divergences that clear all three gates below survive\n\nThe three gates:\n1. Min Momentum Swing — drops differences below this size between the two pivot momentum values\n2. Min Price Swing (%) — drops divergences where price barely moved relative to recent range\n3. Flux Confirmation — Flux must agree with the divergence direction (Bull div needs Flux > 0, Bear div needs Flux < 0)\n\nTurn ON for fewer, higher-conviction signals only.")

sdfMinMom = input.float(10.0, "Min Momentum Swing",
     minval = 1.0, maxval = 50.0, step = 0.5,
     group   = GRP_DIV,
     tooltip = "Minimum momentum swing between the two divergence pivots.\n\nSmall (1–5) → permissive, allows minor divergences through\nMedium (10) → balanced — default\nLarge (20–50) → only structurally significant divergences pass\n\nRequires Smart Filter ON.")

sdfMinPct = input.float(0.3, "Min Price Swing (%)",
     minval = 0.1, maxval = 5.0, step = 0.1,
     group   = GRP_DIV,
     tooltip = "Minimum price swing between divergence pivots as a percentage of the recent (momLen × 4 bars) high-low range.\n\nFilters divergences caused by tiny price moves relative to volatility.\n\n0.3% → permissive — default\n1.0% → moderate\n2.0%+ → strict\n\nRequires Smart Filter ON.")

sdfFluxConf = input.bool(true, "Require Flux Confirmation",
     group   = GRP_DIV,
     tooltip = "When ON, Flux direction must agree with the divergence direction at the moment of detection:\n\n• Bullish divergence → Flux value must be > 0 (uptrend bias)\n• Bearish divergence → Flux value must be < 0 (downtrend bias)\n\nFilters out divergences that fire counter to the broader directional bias. Most useful when the Flux engine is set to a longer length than Momentum.\n\nRequires Smart Filter ON. Default: ON.")

regimeOn = input.bool(true, "Show Regime",
     group   = GRP_REGIME,
     tooltip = "Master toggle for the Trend Regime Detector. When ON, the Dashboard adds a Regime row showing the current market state (⯅ TRENDING UP / ⯆ TRENDING DOWN / ▣ RANGING / ▤ TRANSITION) computed from a built-in ADX + DI± classifier.\n\nWhen OFF, the Regime row hides and the Adaptive Signal Threshold feature is disabled regardless of its own toggle.\n\nDefault: ON.")

regimeLen = input.int(14, "ADX Length",
     minval = 5, maxval = 50, step = 1,
     group   = GRP_REGIME,
     tooltip = "Lookback for the ADX calculation used by the Regime Detector. The standard 14 matches most charting platforms.\n\n7–10 → very reactive (catches early regime shifts)\n14 → balanced — default\n21–28 → smooth (only major, sustained regime changes register)\n\nDefault: 14")

regimeTrendTh = input.float(25.0, "Trend Threshold",
     minval = 15.0, maxval = 50.0, step = 1.0,
     group   = GRP_REGIME,
     tooltip = "ADX value above which the market is classified as TRENDING. Standard convention: ADX > 25 = trend present, ADX < 20 = ranging market.\n\n20 → permissive, many bars classified as trending\n25 → balanced — default\n30+ → strict, only strong trends classified as TRENDING\n\nDefault: 25")

regimeRangeTh = input.float(20.0, "Range Threshold",
     minval = 10.0, maxval = 25.0, step = 1.0,
     group   = GRP_REGIME,
     tooltip = "ADX value below which the market is classified as RANGING. The band between Range and Trend thresholds is TRANSITION (low confidence — neither state strongly active).\n\n15 → strict (only deep range classified as RANGING)\n20 → balanced — default\n22+ → permissive (more bars classified as RANGING)\n\nDefault: 20")

regimeAdaptive = input.bool(false, "Auto-Adjust Signal Threshold",
     group   = GRP_REGIME,
     tooltip = "When ON, the Confluence Signal Threshold auto-adjusts based on the detected regime so Confluence Buy / Sell arrows match the active market state:\n\n• TRENDING → threshold − 10 (permissive; momentum continuation signals welcome)\n• RANGING → threshold + 10 (strict; only deep-reversion signals fire)\n• TRANSITION → unchanged (your manual threshold)\n\nUse for context-aware signal generation that respects the market state. Default: OFF (manual threshold respected as-is).")

barMode = input.string("None", "Bar Color Mode",
     options = ["None", "Momentum", "Flux", "Squeeze", "Confluence", "Slope"],
     group   = GRP_BAR,
     tooltip = "Applies a state-driven colour to every price bar on the chart.\n\nNone → leave bars untouched (default)\nMomentum → bull above zero, bear below zero\nFlux → bull when flux > 0, bear when flux < 0\nSqueeze → squeeze colour ramp when compressed, neutral otherwise\nConfluence → strong / weak / none tiers\nSlope → bull when mom > signal, bear when mom < signal\n\nDefault: None")

showMTF = input.bool(true, "Show MTF Panel",
     group   = GRP_MTF,
     tooltip = "Master toggle for the Multi-Timeframe Confluence panel. The panel runs the full Momentum + Flux + Confluence stack on four higher timeframes simultaneously and shows each TF's bias as a separate row.\n\nThe header tag shows the overall alignment state:\n• ▲▲▲▲ ALIGNED — all four TFs bullish (highest-conviction long setup)\n• ▼▼▼▼ ALIGNED — all four TFs bearish (highest-conviction short setup)\n• ◈ MIXED — TFs disagree (no clean direction)\n\nAll MTF calls use lookahead_off — fully repaint-safe on every closed bar.")

mtfPreset = input.string("Swing", "Timeframe Preset",
     options = ["Scalp", "Intraday", "Swing", "Position", "Crypto", "Forex"],
     group   = GRP_MTF,
     tooltip = "Pre-tuned four-timeframe sets matched to common trader profiles:\n\nScalp: 1m / 5m / 15m / 1h — fast scalper\nIntraday: 5m / 15m / 1h / 4h — day trader\nSwing: 15m / 1h / 4h / 1D — default, swing trader\nPosition: 1h / 4h / 1D / 1W — position trader\nCrypto: 5m / 15m / 1h / 4h — 24/7 markets\nForex: 15m / 1h / 4h / 1D — session-based markets\n\nDefault: Swing")

mtfPos = input.string("Top Right", "Panel Position",
     options = ["Top Right", "Top Left", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"],
     group   = GRP_MTF,
     tooltip = "Anchor position for the MTF Confluence panel inside the indicator pane. Default is Top Right so it docks vertically opposite the main Dashboard (Bottom Right) without overlapping. Six slots — pick whichever clears your other indicators.")

mtfSize = input.string("Small", "Panel Text Size",
     options = ["Tiny", "Small", "Normal", "Large"],
     group   = GRP_MTF,
     tooltip = "Text size inside the MTF Confluence panel. Defaults to Small to mirror the main Dashboard size.")

showDash = input.bool(true, "Show Dashboard",
     group   = GRP_DASH,
     tooltip = "Master toggle for the on-chart data panel.\n\nShows at a glance:\n• Bias — Strong / Weak Bull / Bear / Neutral from mom + flux agreement\n• TS Score — composite 0–100 trend strength reading (RSI-style)\n• Momentum — current momentum value + trend arrow\n• Flux — current flux value + trend arrow\n• Squeeze — Tight / Mid / Loose / — compression tier\n• Confluence — Strong / Weak / None tag\n• Div — most recent divergence detected within the last 50 bars\n• Slope — ▲ momentum above signal, ▼ below\n\nColours are driven by the active Theme. On Midnight / Graphite themes the panel automatically flips to a light background so the text stays readable against dark plots.")

dashPos = input.string("Bottom Right", "Panel Position",
     options = ["Top Right", "Top Left", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"],
     group   = GRP_DASH,
     tooltip = "Anchor position inside the indicator pane where the dashboard docks.\n\nSix slots — three vertical bands × two sides. Pick whichever does not overlap your other indicators or labels.\n\nDefault: Bottom Right (pairs with MTF panel at Top Right — vertically separated to avoid overlap).")

dashSize = input.string("Small", "Panel Text Size",
     options = ["Tiny", "Small", "Normal", "Large"],
     group   = GRP_DASH,
     tooltip = "Text size inside the dashboard.\n\nTiny → smallest, compact layouts\nSmall → default, clean and readable\nNormal → larger, comfortable reading\nLarge → maximum visibility")

simple bool alrtBuy       = input.bool(true,  "Confluence Buy",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum crosses ABOVE the signal line while below −Threshold AND Flux is bearish — classical mean-reversion long trigger inside a downtrend. Threshold is the Confluence Gauges → Signal Threshold setting. Respects the Volume Confirmation gate when enabled, so the alert and the on-chart ▲ arrow always agree.")

simple bool alrtSell      = input.bool(true,  "Confluence Sell",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum crosses BELOW the signal line while above +Threshold AND Flux is bullish — classical mean-reversion short trigger inside an uptrend. Threshold is the Confluence Gauges → Signal Threshold setting. Respects the Volume Confirmation gate when enabled, so the alert and the on-chart ▼ arrow always agree.")

simple bool alrtMomUp     = input.bool(true,  "Momentum Cross Up",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum crosses above zero (bullish regime flip).")

simple bool alrtMomDn     = input.bool(true,  "Momentum Cross Down",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum crosses below zero (bearish regime flip).")

simple bool alrtFluxUp    = input.bool(true,  "Flux Cross Up",
     group   = GRP_ALRT,
     tooltip = "Fires when Flux crosses above zero (bullish directional flip).")

simple bool alrtFluxDn    = input.bool(true,  "Flux Cross Down",
     group   = GRP_ALRT,
     tooltip = "Fires when Flux crosses below zero (bearish directional flip).")

simple bool alrtSwingUp   = input.bool(false, "Bullish Swing",
     group   = GRP_ALRT,
     tooltip = "Fires on every momentum × signal upward cross, regardless of zone. Frequent on short timeframes — best combined with Confluence or Trend alerts for confirmation.")

simple bool alrtSwingDn   = input.bool(false, "Bearish Swing",
     group   = GRP_ALRT,
     tooltip = "Fires on every momentum × signal downward cross, regardless of zone. Frequent on short timeframes — best combined with Confluence or Trend alerts for confirmation.")

simple bool alrtConfBull  = input.bool(true,  "Strong Bull Confluence",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum AND flux both turn bullish (full strong-bull state activates the upper confluence gauge).")

simple bool alrtConfBear  = input.bool(true,  "Strong Bear Confluence",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum AND flux both turn bearish (full strong-bear state activates the lower confluence gauge).")

simple bool alrtWeakBull  = input.bool(false, "Weak Bull Confluence",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum OR flux (but not both) turns bullish (partial bull state — weaker confluence). OFF by default.")

simple bool alrtWeakBear  = input.bool(false, "Weak Bear Confluence",
     group   = GRP_ALRT,
     tooltip = "Fires when momentum OR flux (but not both) turns bearish. OFF by default.")

simple bool alrtSqzTight  = input.bool(true,  "Tight Squeeze",
     group   = GRP_ALRT,
     tooltip = "Fires when stdev drops below ATR × 0.5 — extreme compression, expansion imminent.")

simple bool alrtSqzMid    = input.bool(false, "Mid Squeeze",
     group   = GRP_ALRT,
     tooltip = "Fires when stdev drops below ATR × 0.75 — moderate compression. OFF by default to avoid noise.")

simple bool alrtSqzLoose  = input.bool(false, "Loose Squeeze",
     group   = GRP_ALRT,
     tooltip = "Fires when stdev drops below ATR × 1.0 — mild compression. OFF by default.")

simple bool alrtDivReg    = input.bool(true,  "Regular Divergence",
     group   = GRP_ALRT,
     tooltip = "Fires on Regular bullish or bearish divergence detection. Respects the Smart Filter when enabled.")

simple bool alrtDivHid    = input.bool(false, "Hidden Divergence",
     group   = GRP_ALRT,
     tooltip = "Fires on Hidden bullish or bearish divergence detection. OFF by default — Hidden divergences fire more frequently than Regular. Respects the Smart Filter when enabled.")

simple bool alrtSqzRelease = input.bool(true,  "Squeeze Release",
     group   = GRP_ALRT,
     tooltip = "Fires on the bar where the squeeze fully ends (stdev re-expanded above ATR × 1.0). Imminent volatility expansion — historically the highest-conviction breakout setup.")

simple bool alrtMtfAlign   = input.bool(true,  "MTF Aligned",
     group   = GRP_ALRT,
     tooltip = "Fires the bar all four MTF timeframes first agree on direction (all bull or all bear). The highest-conviction multi-timeframe confluence setup. Fires once per state change to avoid spam.")

simple bool alrtMtfDiv     = input.bool(false, "MTF Divergence",
     group   = GRP_ALRT,
     tooltip = "Fires the bar the current chart's bias first contradicts the majority of HTF biases (3 or more HTFs against current). Useful as a contrarian / counter-trend warning. OFF by default to keep noise low.")

simple bool alrtRegime     = input.bool(false, "Regime Shift",
     group   = GRP_ALRT,
     tooltip = "Fires the bar the market regime transitions (TRENDING ⇄ RANGING ⇄ TRANSITION). Useful as a strategy-switching signal: trending bias when regime is trending, mean-reversion bias when ranging. OFF by default — regime shifts on long histories can fire frequently.")

method runTr(Bar b) =>
    Bar   bPrev = b[1]
    float prevH = na(bPrev) ? na : bPrev.h
    float prevC = na(bPrev) ? na : bPrev.c
    na(prevH) ? b.h - b.l : math.max(math.max(b.h - b.l, math.abs(b.h - prevC)), math.abs(b.l - prevC))

method runAtr(Bar b, simple int len) =>
    ta.rma(b.runTr(), len)

method runStdev(float src, simple int len) =>
    float meanRun  = 0.0
    float meanPrev = 0.0
    float sqAcc    = 0.0
    for k = 0 to len - 1
        float val = nz(src[k])
        meanPrev := meanRun
        meanRun  := meanRun + (val - meanRun) / (1 + k)
        sqAcc    := sqAcc + (val - meanRun) * (val - meanPrev)
    math.sqrt(sqAcc / (len - 1))

method haBar(Bar b) =>
    var Bar ha = Bar.new(na, na, na, na)

    Bar   haPrev = ha[1]
    float prevO  = na(haPrev) ? na : haPrev.o
    float prevC  = na(haPrev) ? na : haPrev.c
    float haC    = math.avg(b.o, b.h, b.l, b.c)
    float haO    = na(prevO) ? math.avg(b.o, b.c) : math.avg(nz(prevO), nz(prevC))
    float haH    = math.max(b.h, math.max(haO, haC))
    float haL    = math.min(b.l, math.min(haO, haC))
    ha          := Bar.new(haO, haH, haL, haC)
    ha

method computeMom(Bar b, simple int len, simple int sigLen) =>
    float chanHi  = ta.highest(b.h, len)
    float chanLo  = ta.lowest (b.l, len)
    float chanMid = math.avg(chanHi, chanLo)
    float smaMid  = ta.sma(math.avg(b.h, b.l), len)
    float chanRng = chanHi - chanLo

    Bar   bPrev   = b[1]
    float prevC   = na(bPrev) ? na : bPrev.c
    float chanTr  = na(prevC) ? chanRng : math.max(chanRng, math.max(math.abs(chanHi - prevC), math.abs(chanLo - prevC)))
    float chanAtr = chanTr < 1e-10 ? b.runTr() : chanTr
    float momRaw  = (b.c - math.avg(chanMid, smaMid)) / chanAtr * 100.0
    float momVal  = ta.linreg(momRaw, len, 0)
    float momSig  = ta.sma(momVal, sigLen)
    MomReading.new(momVal, momSig)

method computeFlux(Bar b, simple int len) =>
    float tr = b.runAtr(len)
    float trSafe = tr < 1e-10 ? 1e-10 : tr
    float up = ta.rma(math.max(ta.change(b.h),      0), len) / trSafe
    float dn = ta.rma(math.max(ta.change(b.l) * -1, 0), len) / trSafe
    float denom = up + dn
    float ratio = denom < 1e-10 ? 0.0 : (up - dn) / denom
    float fluxVal = ta.rma(ratio, len / 2) * 100.0
    float fluxOf  = fluxVal > +25 ? fluxVal - 25 : fluxVal < -25 ? fluxVal + 25 : na
    FluxReading.new(fluxVal, fluxOf)

method detectSqueeze(Bar b, simple int len) =>
    float dev = b.c.runStdev(len)
    float atr = b.runAtr(len)
    bool  sqzTight = dev < atr * 0.5
    bool  sqzMid   = dev < atr * 0.75
    bool  sqzLoose = dev < atr * 1.0
    SqueezeState.new(sqzTight, sqzMid, sqzLoose)

Bar barRaw = Bar.new(open, high, low, close)
Bar barFlx = fluxHA ? barRaw.haBar() : barRaw

MomReading    mom = barRaw.computeMom    (momLen, momSigLen)
FluxReading   flx = barFlx.computeFlux   (fluxLen)
SqueezeState  sqz = barRaw.detectSqueeze (momLen)

float momVal  = mom.value
float momSig  = mom.signal
float fluxVal = flx.value
float fluxOf  = flx.overflow

bool xMomUp   = ta.crossover (momVal, momSig)   // momentum crossed up through signal
bool xMomDn   = ta.crossunder(momVal, momSig)   // momentum crossed down through signal
bool xMomZUp  = ta.crossover (momVal, 0)        // momentum crossed up through zero
bool xMomZDn  = ta.crossunder(momVal, 0)        // momentum crossed down through zero
bool xFluxUp  = ta.crossover (fluxVal, 0)       // flux crossed up through zero
bool xFluxDn  = ta.crossunder(fluxVal, 0)       // flux crossed down through zero

[regimeDiPlus, regimeDiMinus, regimeAdx] = ta.dmi(regimeLen, regimeLen)
bool   regimeTrending  = regimeOn and regimeAdx > regimeTrendTh
bool   regimeRanging   = regimeOn and regimeAdx < regimeRangeTh
bool   regimeBullTrend = regimeTrending and regimeDiPlus >  regimeDiMinus
bool   regimeBearTrend = regimeTrending and regimeDiPlus <= regimeDiMinus
int    regimeCode      = (regimeBullTrend ?  2 :
                          regimeBearTrend ? -2 :
                          regimeRanging   ?  1 :
                                             0)
string regimeTag       = (regimeBullTrend ? "⯅ TRENDING UP" :
                          regimeBearTrend ? "⯆ TRENDING DOWN" :
                          regimeRanging   ? "▣ RANGING" :
                          regimeOn        ? "▤ TRANSITION" :
                                            "—")

bool   regimeShift     = regimeOn and regimeCode != nz(regimeCode[1], regimeCode)

int  confThreshAdj    = (regimeAdaptive and regimeOn ?
                            (regimeTrending ? -10 : regimeRanging ? 10 : 0) : 0)
int  confThreshActive = math.max(1, confThresh + confThreshAdj)

float volAvg    = ta.sma(volume, volMaLen)
bool  volHasData = not na(volume) and volume > 0 and not na(volAvg) and volAvg > 0
bool  volPass    = not volConfOn or not volHasData or volume > volAvg

bool buySignal  = xMomUp and momVal < -confThreshActive and fluxVal < 0 and volPass   // confluence buy
bool sellSignal = xMomDn and momVal >  confThreshActive and fluxVal > 0 and volPass   // confluence sell

bool confStrongBull = fluxVal > 0 and momVal > 0
bool confStrongBear = fluxVal < 0 and momVal < 0
bool confWeakBull   = (fluxVal > 0 or momVal > 0) and not confStrongBull and not confStrongBear
bool confWeakBear   = (fluxVal < 0 or momVal < 0) and not confStrongBull and not confStrongBear

bool justStrongBull = confStrongBull and not confStrongBull[1]
bool justStrongBear = confStrongBear and not confStrongBear[1]
bool justWeakBull   = confWeakBull   and not confWeakBull[1]
bool justWeakBear   = confWeakBear   and not confWeakB

Показано первые 50% кода (символов: 52390)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
5 239₽ ≈ $64.03