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

Momentum Confluence Engine

momentum confluence engine.pine

Похожие материалы по тегам

volatility_gold_master.mq5MQL5 / MetaTrader 5 · 2 общих теговindicator stormcore smc & divergence master for tradingview.pineTradingView · 2 общих теговindicator god mode x - structure and confluence dashboard for tradingview.pineTradingView · 2 общих теговindicator momentum confluence engine for tradingview.pineTradingView · 2 общих теговindicator bitcoin sniper confluence for tradingview.pineTradingView · 2 общих теговbitcoin sniper confluence.pineTradingView · 2 общих тегов
Вы автор или правообладатель?

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

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

О программе

Momentum Confluence Engine — индикатор анализа для TradingView, который объединяет шесть технических индикаторов (RSI, стохастик, CCI, MACD, ROC, MFI) в единый взвешенный «Momentum Score» и отображает его на графике. Индикатор генерирует сигналы BULL/BEAR при пересечении оценкой сигнальной линии, с возможностью фильтрации по согласию компонентов, наклону, таймфрейму и силе тренда. Встроен инструмент управления сделками со стоп-лоссом на базе ATR и тремя целями (TP1–TP3), а также панель мониторинга с информацией о состоянии торговли и компонентах.

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

НастройкаОписание
i_src Ценовой ряд, используемый RSI, стохастиком, CCI, MACD и ROC. MFI всегда читает среднее high-low-close бара.
i_smooth Длина EMA, сглаживающей взвешенную оценку. Больше — медленнее, с меньшим количеством пересечений.
i_sigLen Длина EMA сигнальной линии, рассчитанной от сглаженной оценки. Пересечение оценки этой линией генерирует сырой сигнал.
i_thrBull Оценка при или выше этого уровня читается как BULL в строке Bias панели мониторинга.
i_thrBear Оценка при или ниже этого уровня считается BEAR в строке Bias панели мониторинга.
i_ob Уровень, при котором оценка считается перекупленной: открывает верхнюю зону и отображает OVERBOUGHT в строке состояния зоны.
i_os Уровень, при котором оценка считается перепроданной: открывает нижнюю зону и отображает OVERSOLD в строке состояния зоны.
i_normLen Количество баров для нормализации гистограммы MACD и ROC в z-оценку. Эти компоненты не дают показаний до заполнения этого окна и своих длин.
i_satZ Z-оценка, при которой нормализованный компонент достигает 100 или -100. При меньшем значении насыщение наступает раньше.
i_minAgree Минимальная доля общего веса компонентов, которая должна указывать в ту же сторону, что и сторона сигнала, для прохождения сигнала.
i_reqSlope При включении бычий сигнал также требует роста оценки, а медвежий — падения, за Slope Len баров.
i_slopeLen Количество баров, за которые измеряется изменение оценки для направления наклона и строки наклона.
i_htfOn Включает подтверждение более высокого таймфрейма: бычий сигнал также требует состояния BULL на старшем таймфрейме, медвежий — BEAR. NEUTRAL блокирует оба.
i_htfTf Таймфрейм, состояние которого подтверждает сигналы. Равный графику — корректен, ниже — пропускается.
i_adxOn Включает фильтр силы тренда: сигнал проходит только при ADX не ниже заданного порога, считанного на баре сигнала.
i_adxThr Минимальное значение ADX, необходимое для прохождения сигнала при включённом фильтре силы тренда.
i_adxLen Длина в барах для расчёта направленного движения и усреднения ADX.
i_smMode Метод сглаживания взвешенной оценки перед EMA сглаживания и перед получением сигнала. Доступны: None, SMA, EMA, RMA, WMA, HMA.
i_smLen Длина в барах метода сглаживания. Оценка не имеет показания, пока метод не заполнит это количество баров после первого показания компонента. Не используется при режиме None.
i_useRsi Включает RSI во взвешенную смесь.
i_rsiLen Длина RSI в барах.
i_wRsi Вес компонента RSI во взвешенной смеси.
i_useSto Включает сглаженный стохастик во взвешенную смесь.
i_stoLen Период обратного отсчёта стохастика в барах.
i_stoSm Длина SMA, сглаживающей сырой стохастик.
i_wSto Вес компонента стохастика во взвешенной смеси.
i_useCci Включает CCI во взвешенную смесь.
i_cciLen Длина CCI в барах.
i_cciSat Значение CCI, которому соответствует 100 или -100. Показания за его пределами ограничиваются.
i_wCci Вес компонента CCI во взвешенной смеси.
i_useMacd Включает гистограмму MACD, нормализованную в z-оценку, во взвешенную смесь.
i_wMacd Вес компонента MACD во взвешенной смеси.
i_macdFast Длина быстрой EMA MACD. Если больше медленной, значения меняются местами.
i_macdSlow Длина медленной EMA MACD.
i_macdSig Длина сигнальной EMA MACD.
i_useRoc Включает скорость изменения (ROC), нормализованную в z-оценку, во взвешенную смесь.
i_rocLen Период обратного отсчёта ROC в барах.
i_wRoc Вес компонента ROC во взвешенной смеси.
i_useMfi Включает MFI во взвешенную смесь. MFI основан на объёме.
i_mfiLen Длина MFI в барах. MFI основан на объёме.
i_wMfi Вес компонента MFI во взвешенной смеси.
i_lockSignal Замораживает текущий сигнал и блокирует появление новых.
i_atrLen Количество баров для расчёта ATR, задающего расстояние стоп-лосса. Сделка не открывается, пока ATR имеет значение.
i_slMult Расстояние стоп-лосса в ATR от цены входа (закрытие бара сигнала).
i_tp1R Расстояние первой цели как кратное расстоянию стопа. Цели, заданные не по порядку, сортируются от ближайшей к дальней.
i_tp2R Расстояние второй цели как кратное расстоянию стопа.
i_tp3R Расстояние третьей цели как кратное расстоянию стопа. Достижение закрывает сделку.
i_showMark Рисует маркеры BULL и BEAR на подтверждённых сигналах в панели и на графике цены.
i_showLevels Отображает линии стопа, входа и целей, а также метки для текущей сделки.
i_showCdl Окрашивает свечи цены по градиенту оценки.
i_showZone Заливает зоны перекупленности и перепроданности.
i_showComp Отображает оценку каждого компонента, имеющего показания, в виде отдельной линии.
i_showDash Показывает таблицу панели мониторинга.
i_dashPos Угол, в котором располагается панель мониторинга.
i_dashOnPrice При включении панель мониторинга отображается на графике цены, при выключении — в панели индикатора.
i_actionLong Слово действия, отправляемое в полезной нагрузке оповещения при сигнале на вход в длинную сделку.
i_actionShort Слово действия, отправляемое в полезной нагрузке оповещения при сигнале на вход в короткую сделку.
i_actionCloseLong Слово действия, отправляемое в полезной нагрузке оповещения при закрытии длинной сделки: по финальной цели, стопу или замене новым сигналом.
i_actionCloseShort Слово действия, отправляемое в полезной нагрузке оповещения при закрытии короткой сделки: по финальной цели, стопу или замене новым сигналом.
i_actionPartLong Слово действия, отправляемое в полезной нагрузке оповещения при достижении TP1 или TP2 длинной сделки, когда сделка остаётся открытой.
i_actionPartShort Слово действия, отправляемое в полезной нагрузке оповещения при достижении TP1 или TP2 короткой сделки, когда сделка остаётся открытой.
C_SUP Цвет бычьей зоны градиента оценки, маркеров BULL и бычьих состояний панели.
C_RES Цвет медвежьей зоны градиента оценки, маркеров BEAR и медвежьих состояний панели.
C_NEU Цвет нейтральной зоны градиента оценки.
C_SIG Цвет сигнальной линии.
C_MRK_TXT Цвет текста маркеров BULL и BEAR.
C_MID Цвет нулевой линии.
C_LVL Цвет линий уровней: линии перекупленности, перепроданности, порогов и максимума/минимума.
C_ZONE Цвет заливки зон перекупленности и перепроданности.
C_RSI Цвет линии компонента RSI.
C_STO Цвет линии компонента стохастика.
C_CCI Цвет линии компонента CCI.
C_MACD Цвет линии компонента MACD.
C_ROC Цвет линии компонента ROC.
C_MFI Цвет линии компонента MFI.
C_DASH_HDR Цвет заливки заголовочной строки панели мониторинга.
C_DASH_BG Фон панели мониторинга. Чередующиеся строки используют ослабленную версию этого цвета с прозрачностью 40.
C_DASH_TXT Цвет текста на панели мониторинга. Ячейки меток используют ослабленную версию с прозрачностью 25.
C_WARN Цвет заливки строк панели, отображающих предупреждения.
C_SL Цвет линии стоп-лосса.
C_ENTRY Цвет линии входа в сделку.
C_TP1 Цвет линии первой цели (TP1).
C_TP2 Цвет линии второй цели (TP2).
C_TP3 Цвет линии третьей цели (TP3).
C_LBL_TXT Цвет текста меток уровней сделки.

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

indicator("Momentum Confluence Engine @VipForexCloud", overlay = false, precision = 2, max_labels_count = 500)

const string GRP_CORE  = "⚙️ Core"
const string GRP_FILT  = "🕯️ Filters"
const string GRP_COMP  = "🌊 Components"
const string GRP_TRADE = "📐 Trade Tools"
const string GRP_VIS   = "🎨 Visuals"
const string GRP_DASH  = "📊 Dashboard"
const string GRP_WH    = "🔔 Alerts"
const string GRP_COL   = "🌈 Colors"

i_src       = input.source(close, "Source", group = GRP_CORE, tooltip = "Price series read by RSI, Stoch, CCI, MACD and ROC. MFI always reads the bar's high-low-close average.")
i_smooth    = input.int(3,     "Smooth",   minval = 1,    maxval = 50,   group = GRP_CORE, tooltip = "EMA length that smooths the blended score. Higher is slower with fewer crossovers.")
i_sigLen    = input.int(9,     "Signal Len", minval = 1,  maxval = 100,  group = GRP_CORE, tooltip = "EMA length of the signal line, taken from the smoothed score. A score crossing this line raises a raw signal.")
i_thrBull   = input.int(20,    "Bull Thr", minval = 0,    maxval = 100,  group = GRP_CORE, tooltip = "Score at or above this level reads BULL on the Bias row of the dashboard.")
i_thrBear   = input.int(-20,   "Bear Thr", minval = -100, maxval = 0,    group = GRP_CORE, tooltip = "Score at or below this level reads BEAR on the Bias row of the dashboard.")
i_ob        = input.int(60,    "OB Lvl",   minval = 0,    maxval = 100,  group = GRP_CORE, tooltip = "Score at or above this level is overbought: it opens the upper zone and reads OVERBOUGHT on the Zone row.")
i_os        = input.int(-60,   "OS Lvl",   minval = -100, maxval = 0,    group = GRP_CORE, tooltip = "Score at or below this level is oversold: it opens the lower zone and reads OVERSOLD on the Zone row.")
i_normLen   = input.int(100,   "Norm Len", minval = 20,   maxval = 500,  group = GRP_CORE, tooltip = "Bars used to turn the MACD histogram and ROC into z-scores. Those two components give no reading until this window and their own lengths have filled.")
i_satZ      = input.float(2.5, "Z Sat",    minval = 1.0,  maxval = 5.0, step = 0.1, group = GRP_CORE, tooltip = "Z-score at which a normalised component reaches 100 or -100. Lower saturates sooner.")

i_minAgree  = input.int(60,   "Min Agree %", minval = 0, maxval = 100, group = GRP_FILT, tooltip = "Minimum share of the total component weight that must point the same way as the signal side (score above its signal line is the bull side, below it the bear side) for a signal to pass.")
i_reqSlope  = input.bool(true, "Slope Align", group = GRP_FILT, tooltip = "A bull signal also needs the score rising, and a bear signal falling, over Slope Len bars.")
i_slopeLen  = input.int(3, "Slope Len", minval = 1, maxval = 50, group = GRP_FILT, tooltip = "Bars over which the change in the score is measured for Slope Align and the Slope row.")
i_htfOn     = input.bool(false, "Higher TF Confirm", group = GRP_FILT, tooltip = "A bull signal also needs the higher timeframe's Bias state to be BULL and a bear signal BEAR; NEUTRAL blocks both. The state is this indicator's own score against Bull Thr and Bear Thr, with the same settings, read on the last confirmed higher-timeframe bar. It reads once the higher timeframe's own score has a reading, with the same warm-up as the Score row on that timeframe, plus one confirmed higher-timeframe bar; until then every signal is blocked.")
i_htfTf     = input.timeframe("D", "Higher TF", group = GRP_FILT, tooltip = "Timeframe whose Bias state confirms signals. A timeframe equal to the chart's is valid and reads the chart's own state. A timeframe lower than the chart's is skipped and passes every signal.")
i_adxOn     = input.bool(false, "Strength Filter", group = GRP_FILT, tooltip = "A signal also needs ADX at or above ADX Threshold, read on the signal bar and acted on at its confirmed close.")
i_adxThr    = input.float(20.0, "ADX Threshold", minval = 0.0, maxval = 100.0, group = GRP_FILT, tooltip = "Minimum ADX a signal needs while Strength Filter is on.")
i_adxLen    = input.int(14, "ADX Length", minval = 1, group = GRP_FILT, tooltip = "Length of the directional movement and of the ADX average, in bars.")
i_smMode    = input.string("None", "Smoothing", options = ["None", "SMA", "EMA", "RMA", "WMA", "HMA"], group = GRP_FILT, tooltip = "Method that smooths the blended score before the Smooth EMA and before any signal is derived from it. None leaves the score as it is.")
i_smLen     = input.int(20, "Smoothing Length", minval = 1, group = GRP_FILT, tooltip = "Length of the Smoothing method in bars. The score has no reading until the method has filled this many bars after the first component reading. Not used while Smoothing is None.")

i_useRsi    = input.bool(true,  "RSI",   inline = "R", group = GRP_COMP, tooltip = "Include RSI in the weighted blend.")
i_rsiLen    = input.int(14,     "",   inline = "R", minval = 2, maxval = 500, group = GRP_COMP, tooltip = "RSI length in bars.")
i_wRsi      = input.float(1.0,  "",     inline = "R", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "RSI row. The first box includes RSI in the weighted blend, Len is its length in bars and W its weight. RSI leaves the score when it is switched off, W is 0, the chart is not a standard chart, or until the RSI length has filled.")
i_useSto    = input.bool(true,  "Stoch", inline = "S", group = GRP_COMP, tooltip = "Include the smoothed stochastic in the weighted blend.")
i_stoLen    = input.int(14,     "",   inline = "S", minval = 2, maxval = 500, group = GRP_COMP, tooltip = "Stochastic lookback length in bars.")
i_stoSm     = input.int(3,      "",    inline = "S", minval = 1, maxval = 50, group = GRP_COMP, tooltip = "SMA length that smooths the raw stochastic.")
i_wSto      = input.float(1.0,  "",     inline = "S", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "Stoch row. The first box includes the smoothed stochastic in the weighted blend, Len is its lookback in bars, Sm the SMA length that smooths the raw stochastic and W its weight. The stochastic leaves the score when it is switched off, W is 0, the chart is not a standard chart, or until Len and then Sm have filled.")
i_useCci    = input.bool(true,  "CCI",   inline = "C", group = GRP_COMP, tooltip = "Include CCI in the weighted blend.")
i_cciLen    = input.int(20,     "",   inline = "C", minval = 2, maxval = 500, group = GRP_COMP, tooltip = "CCI length in bars.")
i_cciSat    = input.float(200., "",   inline = "C", minval = 50.0, maxval = 500.0, step = 10.0, group = GRP_COMP, tooltip = "CCI value that maps to 100 or -100. Readings beyond it are clamped.")
i_wCci      = input.float(1.0,  "",     inline = "C", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "CCI row. The first box includes CCI in the weighted blend, Len is its length in bars, Sat the CCI value that maps to 100 or -100 (readings beyond it are clamped) and W its weight. CCI leaves the score when it is switched off, W is 0, the chart is not a standard chart, or until the CCI length has filled.")
i_useMacd   = input.bool(true,  "MACD",  inline = "M", group = GRP_COMP, tooltip = "Include the MACD histogram, normalised to a z-score over Norm Len bars, in the weighted blend.")
i_wMacd     = input.float(1.0,  "",     inline = "M", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "MACD row. The first box includes the MACD histogram, normalised to a z-score over Norm Len bars, in the weighted blend and W is its weight. MACD leaves the score when it is switched off, W is 0, the chart is not a standard chart, its window is flat, or until the MACD lengths and then Norm Len bars have filled.")
i_macdFast  = input.int(12,     "Fast",  inline = "N", minval = 1, maxval = 500, group = GRP_COMP, tooltip = "MACD fast EMA length. If it is above Slow, the two are swapped.")
i_macdSlow  = input.int(26,     "",  inline = "N", minval = 2, maxval = 500, group = GRP_COMP, tooltip = "MACD slow EMA length.")
i_macdSig   = input.int(9,      "",   inline = "N", minval = 1, maxval = 500, group = GRP_COMP, tooltip = "MACD lengths. Fast and Slow are the fast and slow EMA lengths (if Fast is above Slow, the two are swapped) and Sig is the signal EMA length. MACD leaves the score until these lengths and then Norm Len bars have filled, or while its window is flat.")
i_useRoc    = input.bool(true,  "ROC",   inline = "O", group = GRP_COMP, tooltip = "Include rate of change, normalised to a z-score over Norm Len bars, in the weighted blend.")
i_rocLen    = input.int(14,     "",   inline = "O", minval = 1, maxval = 500, group = GRP_COMP, tooltip = "ROC lookback in bars.")
i_wRoc      = input.float(1.0,  "",     inline = "O", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "ROC row. The first box includes rate of change, normalised to a z-score over Norm Len bars, in the weighted blend, Len is its lookback in bars and W its weight. ROC leaves the score when it is switched off, W is 0, the chart is not a standard chart, its window is flat, or until the ROC length and then Norm Len bars have filled.")
i_useMfi    = input.bool(true,  "MFI",   inline = "F", group = GRP_COMP, tooltip = "Include MFI in the weighted blend. MFI is volume-based.")
i_mfiLen    = input.int(14,     "",   inline = "F", minval = 2, maxval = 500, group = GRP_COMP, tooltip = "MFI length in bars.")
i_wMfi      = input.float(1.0,  "",     inline = "F", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_COMP, tooltip = "MFI row. The first box includes MFI in the weighted blend, Len is its length in bars and W its weight. MFI is volume-based. MFI leaves the score when it is switched off, W is 0, the chart is not a standard chart, or until the MFI length has filled.")

i_lockSignal = input.bool(false, "Lock Signal", group = GRP_TRADE, tooltip = "Freeze current signal · block new ones")
i_atrLen    = input.int(14,    "ATR Length", minval = 1,   maxval = 500, group = GRP_TRADE, tooltip = "Bars in the ATR that sets the stop distance. No trade is armed until the ATR has a value.")
i_slMult    = input.float(1.5, "SL ATR x",   minval = 0.1, step = 0.1,   group = GRP_TRADE, tooltip = "Stop distance in ATR from the entry, which is the close of the signal bar.")
i_tp1R      = input.float(1.0, "TP1 R",      minval = 0.1, step = 0.1,   group = GRP_TRADE, tooltip = "Target distance as a multiple of the stop distance. Targets set out of order are sorted nearest to farthest.")
i_tp2R      = input.float(2.0, "TP2 R",      minval = 0.1, step = 0.1,   group = GRP_TRADE, tooltip = "Second target distance as a multiple of the stop distance.")
i_tp3R      = input.float(3.0, "TP3 R",      minval = 0.1, step = 0.1,   group = GRP_TRADE, tooltip = "Third and final target distance as a multiple of the stop distance. Reaching it closes the trade.")

i_showMark  = input.bool(true,  "Markers",      group = GRP_VIS, tooltip = "Draw BULL and BEAR markers on confirmed signals, in the pane and on the price chart.")
i_showLevels = input.bool(true, "Trade Levels", group = GRP_VIS, tooltip = "Draws the stop, entry and target lines and labels for the current trade. Hit tracking and alerts run with it off.")
i_showCdl   = input.bool(true,  "Candle Color", group = GRP_VIS, tooltip = "Colour the price candles by the score gradient.")
i_showZone  = input.bool(true,  "OB/OS Zones", group = GRP_VIS, tooltip = "Fill the overbought and oversold zones.")
i_showComp  = input.bool(false, "Components",  group = GRP_VIS, tooltip = "Plot the score of each component that has a reading as its own line.")

i_showDash  = input.bool(true, "Show Dash", group = GRP_DASH, tooltip = "Show the dashboard table.")
i_dashPos   = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = GRP_DASH, tooltip = "Corner the dashboard sits in.")
i_dashOnPrice = input.bool(true, "Show on Price Chart", group = GRP_DASH, tooltip = "On: the dashboard is drawn on the price chart. Off: it stays in this indicator's pane.")

i_actionLong       = input.string("long",             "↑ Long Action",              group = GRP_WH, tooltip = "Action word sent in the alert payload when a long entry is signalled. Quotation marks and backslashes are escaped.")
i_actionShort      = input.string("short",            "↓ Short Action",             group = GRP_WH, tooltip = "Action word sent in the alert payload when a short entry is signalled. Quotation marks and backslashes are escaped.")
i_actionCloseLong  = input.string("closelong",        "✕ Close Long Action",        group = GRP_WH, tooltip = "Action word sent when a long trade closes: final target, stop, or replacement by a new signal. Quotation marks and backslashes are escaped.")
i_actionCloseShort = input.string("closeshort",       "✕ Close Short Action",       group = GRP_WH, tooltip = "Action word sent when a short trade closes: final target, stop, or replacement by a new signal. Quotation marks and backslashes are escaped.")
i_actionPartLong   = input.string("partialcloselong", "✕ Partial Close Long Action", group = GRP_WH, tooltip = "Action word sent when a long trade reaches TP1 or TP2, which leaves the trade open. Quotation marks and backslashes are escaped.")
i_actionPartShort  = input.string("partialcloseshort","✕ Partial Close Short Action",group = GRP_WH, tooltip = "Action word sent when a short trade reaches TP1 or TP2, which leaves the trade open. Quotation marks and backslashes are escaped.")

C_SUP      = input.color(#26a69a, "Bull",        group = GRP_COL, tooltip = "Bullish colour: top of the score gradient, BULL markers and bullish dashboard states.")
C_RES      = input.color(#ef5350, "Bear",        group = GRP_COL, tooltip = "Bearish colour: bottom of the score gradient, BEAR markers and bearish dashboard states.")
C_NEU      = input.color(#f9a825, "Neutral",     group = GRP_COL, tooltip = "Neutral colour: middle of the score gradient.")
C_SIG      = input.color(#b388ff, "Signal Line", group = GRP_COL, tooltip = "Colour of the signal line.")
C_MRK_TXT  = input.color(#ffffff, "Marker Txt",  group = GRP_COL, tooltip = "Text colour of the BULL and BEAR markers.")
C_MID      = input.color(color.new(#787b86, 40), "Mid Line",    group = GRP_COL, tooltip = "Colour of the zero line.")
C_LVL      = input.color(color.new(#787b86, 65), "Level Lines", group = GRP_COL, tooltip = "Colour of the overbought, oversold, threshold and maximum lines.")
C_ZONE     = input.color(color.new(#787b86, 88), "Zone Fill",   group = GRP_COL, tooltip = "Fill colour of the overbought and oversold zones.")
C_RSI      = input.color(#42a5f5, "RSI Line",   group = GRP_COL, tooltip = "Colour of the RSI component line.")
C_STO      = input.color(#ab47bc, "Stoch Line", group = GRP_COL, tooltip = "Colour of the stochastic component line.")
C_CCI      = input.color(#ffa726, "CCI Line",   group = GRP_COL, tooltip = "Colour of the CCI component line.")
C_MACD     = input.color(#26c6da, "MACD Line",  group = GRP_COL, tooltip = "Colour of the MACD component line.")
C_ROC      = input.color(#9ccc65, "ROC Line",   group = GRP_COL, tooltip = "Colour of the ROC component line.")
C_MFI      = input.color(#ec407a, "MFI Line",   group = GRP_COL, tooltip = "Colour of the MFI component line.")
C_DASH_HDR = input.color(color.new(#3a2a6d, 55), "Dash Hdr", group = GRP_COL, tooltip = "Fill colour of the dashboard header row.")
C_DASH_BG  = input.color(color.new(#0a0f1a, 10), "Dash BG",  group = GRP_COL, tooltip = "Dashboard background. Alternate rows use a faded copy of it, at 40 transparency.")
C_DASH_TXT = input.color(#ffffff, "Dash Txt", group = GRP_COL, tooltip = "Dashboard text colour. Label cells use a faded copy of it, at 25 transparency.")
C_WARN     = input.color(color.new(#f9a825, 80), "Warn Fill", group = GRP_COL, tooltip = "Fill of dashboard rows that warn, such as a skipped setting. A row takes it only while it warns.")
C_SL       = input.color(#ef5350, "SL",         group = GRP_COL, tooltip = "Stop line. The stop label uses the same colour at full opacity.")
C_ENTRY    = input.color(#2196f3, "Entry",      group = GRP_COL, tooltip = "Entry line. The entry label uses the same colour at full opacity.")
C_TP1      = input.color(color.new(#26a69a, 40), "TP1", group = GRP_COL, tooltip = "TP1 line. The TP1 label uses the same colour at full opacity.")
C_TP2      = input.color(color.new(#26a69a, 20), "TP2", group = GRP_COL, tooltip = "TP2 line. The TP2 label uses the same colour at full opacity.")
C_TP3      = input.color(color.new(#26a69a, 0),  "TP3", group = GRP_COL, tooltip = "TP3 line. The TP3 label uses the same colour at full opacity.")
C_LBL_TXT  = input.color(#ffffff, "Label Text", group = GRP_COL, tooltip = "Text colour of the trade level labels.")
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @VipForexCloud", text_color = color.new(color.gray, 70), text_size = size.large)

f_clamp(float v, float lim) =>
    math.max(-lim, math.min(lim, v))

f_bounded(float v) =>
    (v - 50.0) * 2.0

f_zScore(float v, int len, float sat) =>
    float _m  = ta.sma(v, len)
    float _sd = ta.stdev(v, len)
    float _z  = na(v) or na(_sd) ? na : _sd > 0.0 ? (v - _m) / _sd : na
    f_clamp(_z / sat * 100.0, 100.0)

f_dir(float v) =>
    v > 0.0 ? 1 : v < 0.0 ? -1 : 0

f_agr(float s, float w, int d) =>
    f_dir(s) == d ? w : 0.0

float _rsiRaw  = ta.rsi(i_src, i_rsiLen)
float _stoRaw  = ta.sma(ta.stoch(i_src, high, low, i_stoLen), i_stoSm)
float _cciRaw  = ta.cci(i_src, i_cciLen)
int _macdF = math.min(i_macdFast, i_macdSlow)
int _macdS = math.max(i_macdFast, i_macdSlow)
[_, _, _macdH] = ta.macd(i_src, _macdF, _macdS, i_macdSig)
float _rocRaw  = ta.roc(i_src, i_rocLen)
float _mfiRaw  = ta.mfi(hlc3, i_mfiLen)
[_, _, _adx] = ta.dmi(i_adxLen, i_adxLen)

float _sRsi  = f_clamp(f_bounded(_rsiRaw), 100.0)
float _sSto  = f_clamp(f_bounded(_stoRaw), 100.0)
float _sCci  = f_clamp(_cciRaw / i_cciSat * 100.0, 100.0)
float _sMacd = f_zScore(_macdH, i_normLen, i_satZ)
float _sRoc  = f_zScore(_rocRaw, i_normLen, i_satZ)
float _sMfi  = f_clamp(f_bounded(_mfiRaw), 100.0)

bool _std = chart.is_standard

bool _okRsi  = _std and i_useRsi  and not na(_sRsi)
bool _okSto  = _std and i_useSto  and not na(_sSto)
bool _okCci  = _std and i_useCci  and not na(_sCci)
bool _okMacd = _std and i_useMacd and not na(_sMacd)
bool _okRoc  = _std and i_useRoc  and not na(_sRoc)
bool _okMfi  = _std and i_useMfi  and not na(_sMfi)

float nRsi  = _okRsi  ? _sRsi  : 0.0
float nSto  = _okSto  ? _sSto  : 0.0
float nCci  = _okCci  ? _sCci  : 0.0
float nMacd = _okMacd ? _sMacd : 0.0
float nRoc  = _okRoc  ? _sRoc  : 0.0
float nMfi  = _okMfi  ? _sMfi  : 0.0

float wRsi  = _okRsi  ? i_wRsi  : 0.0
float wSto  = _okSto  ? i_wSto  : 0.0
float wCci  = _okCci  ? i_wCci  : 0.0
float wMacd = _okMacd ? i_wMacd : 0.0
float wRoc  = _okRoc  ? i_wRoc  : 0.0
float wMfi  = _okMfi  ? i_wMfi  : 0.0

float _wSum = wRsi + wSto + wCci + wMacd + wRoc + wMfi
float _sSum = wRsi * nRsi + wSto * nSto + wCci * nCci + wMacd * nMacd + wRoc * nRoc + wMfi * nMfi
float _raw  = _wSum > 0.0 ? _sSum / _wSum : na
float _smSma = ta.sma(_raw, i_smLen)
float _smEma = ta.ema(_raw, i_smLen)
float _smRma = ta.rma(_raw, i_smLen)
float _smWma = ta.wma(_raw, i_smLen)
float _smHma = ta.hma(_raw, i_smLen)
float _blend = na(_raw) ? na : i_smMode == "SMA" ? _smSma : i_smMode == "EMA" ? _smEma : i_smMode == "RMA" ? _smRma : i_smMode == "WMA" ? _smWma : i_smMode == "HMA" ? _smHma : _raw
float _scoreEma = ta.ema(_blend, i_smooth)
float score = na(_blend) ? na : _scoreEma
float _sigEma = ta.ema(score, i_sigLen)
float signalLine = na(score) ? na : _sigEma

int   _dir   = na(score) or na(signalLine) ? na : score > signalLine ? 1 : score < signalLine ? -1 : 0
float _agrW  = f_agr(nRsi, wRsi, _dir) + f_agr(nSto, wSto, _dir) + f_agr(nCci, wCci, _dir) + f_agr(nMacd, wMacd, _dir) + f_agr(nRoc, wRoc, _dir) + f_agr(nMfi, wMfi, _dir)
float agree  = na(_dir) or _wSum <= 0.0 ? na : _dir != 0 ? _agrW / _wSum * 100.0 : 0.0
int   _active = (_okRsi ? 1 : 0) + (_okSto ? 1 : 0) + (_okCci ? 1 : 0) + (_okMacd ? 1 : 0) + (_okRoc ? 1 : 0) + (_okMfi ? 1 : 0)

float _slopeRaw = ta.change(score, i_slopeLen)
float _slope = nz(_slopeRaw)

bool _agrOk     = not na(agree) and agree >= i_minAgree
bool _xUp       = ta.crossover(score, signalLine)
bool _xDn       = ta.crossunder(score, signalLine)
bool _defNow    = not na(score) and not na(signalLine)
bool _defPrev   = not na(score[1]) and not na(signalLine[1])
bool _rawBull   = _xUp and _defNow and _defPrev
bool _rawBear   = _xDn and _defNow and _defPrev
int  _biasS     = na(score) ? na : score >= i_thrBull ? 1 : score <= i_thrBear ? -1 : 0
int  _htfSec    = timeframe.in_seconds(i_htfTf)
int  _chartSec  = timeframe.in_seconds()
bool _htfSame   = _htfSec == _chartSec
bool _htfSkip   = i_htfOn and _htfSec < _chartSec
int  _htfReq    = i_htfOn and _std and not _htfSame and not _htfSkip ? request.security(syminfo.tickerid, i_htfTf, _biasS[1], lookahead = barmerge.lookahead_on) : na
int  _htfSt     = _htfSame ? _biasS : _htfReq
bool _htfBullOk = not i_htfOn or _htfSkip or _htfSt == 1
bool _htfBearOk = not i_htfOn or _htfSkip or _htfSt == -1
bool _adxOk     = not i_adxOn or (not na(_adx) and _adx >= i_adxThr)
bool bullSignal = _std and _rawBull and _agrOk and (not i_reqSlope or _slope > 0.0) and _htfBullOk and _adxOk
bool bearSignal = _std and _rawBear and _agrOk and (not i_reqSlope or _slope < 0.0) and _htfBearOk and _adxOk

bool _fireBull = bullSignal and barstate.isconfirmed
bool _fireBear = bearSignal and barstate.isconfirmed

float _atr      = ta.atr(i_atrLen)
float _rLo      = math.min(i_tp1R, math.min(i_tp2R, i_tp3R))
float _rHi      = math.max(i_tp1R, math.max(i_tp2R, i_tp3R))
float _rMid     = math.max(math.min(i_tp1R, i_tp2R), math.min(math.max(i_tp1R, i_tp2R), i_tp3R))
bool  _tpReord  = not (i_tp1R <= i_tp2R and i_tp2R <= i_tp3R)
float _entryPx  = close
float _riskDist = _atr * i_slMult
float _slL      = _entryPx - _riskDist
float _tp1L     = _entryPx + _riskDist * _rLo
float _tp2L     = _entryPx + _riskDist * _rMid
float _tp3L     = _entryPx + _riskDist * _rHi
float _slS      = _entryPx + _riskDist
float _tp1S     = _entryPx - _riskDist * _rLo
float _tp2S     = _entryPx - _riskDist * _rMid
float _tp3S     = _entryPx - _riskDist * _rHi
bool  _okL      = _riskDist > syminfo.mintick and _slL > 0.0
bool  _okS      = _riskDist > syminfo.mintick and _tp3S > 0.0
bool  _regBull  = _fireBull and _okL
bool  _regBear  = _fireBear and _okS

var int    tradeDir = 0
var float  tEntry   = na
var float  tSl      = na
var float  tTp1     = na
var float  tTp2     = na
var float  tTp3     = na
var int    sigBar   = int(na)
var int    closeBar = int(na)
var bool   tp1Hit   = false
var bool   tp2Hit   = false
var bool   tp3Hit   = false
var bool   slHit    = false
var int    ld1      = 1
var int    ld2      = 2
var int    ld3      = 3
var string namesE   = "Entry"
var string names1   = "TP1"
var string names2   = "TP2"
var string names3   = "TP3"
var line   slLine    = na
var line   entryLine = na
var line   tp1Line   = na
var line   tp2Line   = na
var line   tp3Line   = na
var label  slLbl     = na
var label  entryLbl  = na
var label  tp1Lbl    = na
var label  tp2Lbl    = na
var label  tp3Lbl    = na

f_pctTxt(float lvl, float entry, bool isLong) =>
    float _p = (isLong ? lvl - entry : entry - lvl) / entry * 100.0
    (_p >= 0.0 ? "+" : "") + str.tostring(_p, "0.00") + "%"

f_deleteLevels() =>
    line.delete(slLine)
    line.delete(entryLine)
    line.delete(tp1Line)
    line.delete(tp2Line)
    line.delete(tp3Line)
    label.delete(slLbl)
    label.delete(entryLbl)
    label.delete(tp1Lbl)
    label.delete(tp2Lbl)
    label.delete(tp3Lbl)

f_ldLbl(int ld) =>
    ld == 0 ? entryLbl : ld == 1 ? tp1Lbl : ld == 2 ? tp2Lbl : tp3Lbl

f_ldNames(int ld) =>
    ld == 0 ? namesE : ld == 1 ? names1 : ld == 2 ? names2 : names3

bool _isLongT  = tradeDir == 1
bool _liveT    = tradeDir != 0 and bar_index > sigBar
bool _tp1Cross = _liveT and (_isLongT ? high >= tTp1 : low <= tTp1)
bool _tp2Cross = _liveT and (_isLongT ? high >= tTp2 : low <= tTp2)
bool _tp3Cross = _liveT and (_isLongT ? high >= tTp3 : low <= tTp3)
bool _slCross  = _liveT and barstate.isconfirmed and (_isLongT ? close < tSl : close > tSl)
bool tp1New = false
bool tp2New = false
bool tp3New = false
bool slNew  = false
if _tp1Cross and not tp1Hit and not slHit
   

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