Momentum Confluence Engine
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator momentum confluence engine for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Momentum Confluence Engine — индикатор анализа для TradingView, который объединяет шесть технических индикаторов (RSI, сглаженный стохастик, CCI, гистограмму MACD, ROC и MFI) в единый взвешенный показатель Momentum Score в диапазоне от -100 до +100. Индикатор отображает этот score на графике вместе со сигнальной линией, зонами перекупленности/перепроданности и линиями компонентов, а также рисует BULL и BEAR метки при подтверждённых пересечениях. Встроенная информационная панель (dashboard) показывает текущие значения всех компонентов, уровень согласия, направление, наклон, состояние тренма и параметры текущей сделки. Индикатор поддерживает оповещения для сигналов входа, частичного закрытия, полного закрытия, а также попаданий стопа и тейков.
Перед генерацией сигнала индикатор применяет несколько фильтров: минимальный процент согласия компонентов, проверку направления наклона score, подтверждение с верхнего таймфрейма и фильтр силы тренма по ADX. Все эти фильтры включаются и настраиваются пользователем. Для визуализации доступны раскраска свечей по градиенту score, заливка зон перекупленности/перепроданности, отображение панели компонентов и настраиваемые цвета для каждого элемента. Расчёты выполняются только на стандартных графиках.
Индикатор содержит инструменты для отображения уровней сделки: стоп-лосс и три тейк-профита рассчитываются на основе ATR от цены закрытия свечи сигнала. Эти уровни отрисовываются линиями и метками на графике с информацией о процентном отклонении. При достижении целей или срабатывании стопа индикатор обновляет соответствующие метки и генерирует оповещения. Важно: это индикатор анализа и отображения, а не стратегия — он не симулирует сделки в тестере.
Настройки программы
| Настройка | Описание |
|---|---|
| i_src | Ценовая серия, используемая для расчёта RSI, стохастика, CCI, MACD и ROC. MFI всегда читает среднее high-low-close свечи. |
| i_smooth | Длина EMA, сглаживающей взвешенный score. Большее значение даёт более медленную реакцию с меньшим пересечениями. |
| i_sigLen | Длина EMA сигнальной линии, рассчитанной от сглаженного score. Пересечение score этой линией генерирует сырой сигнал. |
| i_thrBull | Score на или выше этого уровня отображается как BULL в строке направления панели. |
| i_thrBear | Score на или ниже этого уровня отображается как BEAR в строке направления панели. |
| i_ob | Уровень перекупленности: score на или выше этого уровня открывает верхнюю зону и отображает OVERBOUGHT в строке зон панели. |
| i_os | Уровень перепроданности: score на или ниже этого уровня открывает нижнюю зону и отображает OVERSOLD в строке зон панели. |
| i_normLen | Количество свечей для нормализации гистограммы MACD и ROC в z-оценки. Эти два компонента не дают readings до заполнения этого окна и своих длин. |
| i_satZ | Z-оценка, при которой нормализованный компонент достигает 100 или -100. При меньшем значении насыщение наступает раньше. |
| i_minAgree | Минимальная доля общего веса компонентов, которая должна указывать в ту же сторону, что и сторона сигнала, для прохождения сигнала. |
| i_reqSlope | При включении бычий сигнал также требует, чтобы score рос, а медвежий — падал, на протяжении Slope Len свечей. |
| i_slopeLen | Количество свечей, на протяжении которых измеряется изменение score для проверки наклона и строки наклона на панели. |
| i_htfOn | Включает подтверждение с верхнего таймфрейма: бычий сигнал требует состояние BULL на верхнем таймфрейме, медвежий — BEAR, нейтральное блокирует оба. Состояние — собственный score этого индикатора относительно Bull Thr и Bear Thr с теми же настройками, считывается на последней подтверждённой свече ве |
| i_htfTf | Таймфрейм, состояние которого подтверждает сигналы. Таймфрейм, равный таймфрейму графика, корректен. Таймфрейм ниже графика пропускается и пропускает все сигналы. |
| i_adxOn | Включает фильтр силы тренма: сигнал также требует ADX не ниже порогового значения, считывается на свече сигнала и применяется на её подтверждённом закрытии. |
| i_adxThr | Минимальное значение ADX, необходимое для сигнала при включённом фильтре силы тренма. |
| i_adxLen | Длина в свечах для расчёта направленного движения и усреднения ADX. |
| i_smMode | Метод сглаживания взвешенного score перед EMA сглаживания и перед получением сигнала. Доступны: None, SMA, EMA, RMA, WMA, HMA. |
| i_smLen | Длина метода сглаживания в свечах. Score не имеет readings до заполнения методом этого количества свечей после первого readings компонента. Не используется при Smoothing = 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. Если больше, чем Slow, значения меняются местами. |
| 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 | Раскрашивает свечи цены по градиенту score. |
| i_showZone | Заливает зоны перекупленности и перепроданности. |
| i_showComp | Отображает score каждого компонента, имеющего readings, отдельной линией. |
| i_showDash | Показывает таблицу информационной панели. |
| i_dashPos | Угол, в котором располагается информационная панель. |
| i_dashOnPrice | Определяет, где отображается панель: включено — на графике цены, выключено — в панели индикатора. |
| i_actionLong | Слово действия, отправляемое в полезной нагрузке оповещения при сигнале на вход в длинную позицию. |
| i_actionShort | Слово действия, отправляемое в полезной нагрузке оповещения при сигнале на вход в короткую позицию. |
| i_actionCloseLong | Слово действия, отправляемое в полезной нагрузке оповещения при закрытии длинной позиции: по достижении финального тейка, стопа или замене новым сигналом. |
| i_actionCloseShort | Слово действия, отправляемое в полезной нагрузке оповещения при закрытии короткой позиции: по достижении финального тейка, стопа или замене новым сигналом. |
| i_actionPartLong | Слово действия, отправляемое в полезной нагрузке оповещения при достижении TP1 или TP2 длинной позицией, при которой сделка остаётся открытой. |
| i_actionPartShort | Слово действия, отправляемое в полезной нагрузке оповещения при достижении TP1 или TP2 короткой позицией, при которой сделка остаётся открытой. |
| C_SUP | Цвет бычьей зоны: верхняя часть градиента score, BULL метки и бычьи состояния панели. |
| C_RES | Цвет медвежьей зоны: нижняя часть градиента score, BEAR метки и медвежьи состояния панели. |
| C_NEU | Цвет нейтральной зоны: средняя часть градиента score. |
| 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. Метка TP1 использует этот цвет с полной непрозрачностью. |
| C_TP2 | Цвет линии TP2. Метка TP2 использует этот цвет с полной непрозрачностью. |
| C_TP3 | Цвет линии TP3. Метка TP3 использует этот цвет с полной непрозрачностью. |
| C_LBL_TXT | Цвет текста меток уровней сделки. |
Поиск по коду файла
indicator("Momentum Confluence Engine @simpleforextools", 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 @SimpleForexTools", 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 >Показано первые 50% кода (символов: 38353)