High Probability Price Action IndicatorExplanation of the Code
Price Action Patterns :
Pin Bars : Indicate potential reversals at support or resistance levels.
Engulfing Bars : Show strong bullish or bearish momentum where the current bar engulfs the previous one.
Volume Analysis :
The script calculates the volume percentage as the ratio of the current bar's volume to the average volume over a specified period (volume_avg_length).
A volume percentage greater than 1 indicates above-average volume, which adds weight to the signal.
Liquidity Sweep Detection :
A liquidity sweep occurs when the current bar's high matches the session's high or the low matches the session's low.
The script also checks if the volume percentage exceeds a threshold (liquidity_sweep_threshold) to confirm significant buying or selling pressure.
Signal Generation :
Bullish Signal : Generated when a bullish price action pattern (e.g., pin bar or engulfing bullish) occurs with above-average volume and no liquidity sweep.
Bearish Signal : Generated under similar conditions for bearish patterns.
نماذج فنيه
Heikin Ashi + MACD + RSI + Candlestick + Fibonacci• Heikin Ashi Candles: The script calculates Heikin Ashi values (haOpen, haClose, haHigh, haLow) to identify bullish or bearish candle conditions.
• MACD Signals: Uses a fast and slow EMA on the Heikin Ashi close, along with a signal line, to detect bullish (crossover) or bearish (crossunder) momentum shifts.
• RSI Filter: Applies RSI with adjustable overbought/oversold levels to refine bullish or bearish signals and to detect potential divergences.
• Candlestick Patterns: Checks for bullish/bearish engulfing and three-line strike patterns, integrating them into the overall signal logic.
• RSI Divergence: Identifies bullish or bearish divergence by comparing recent price lows/highs with RSI lows/highs.
• Base Buy/Sell Signals: Combines MACD crosses, RSI overbought/oversold, candlestick patterns, and divergence into single buy or sell triggers.
• Fibonacci for Entry Filtering (Optional): Uses pivot highs/lows to calculate Fibonacci retracement levels; signals only trigger if price is near these retracement zones (when enabled).
• ATR-Based Stops/Targets: Calculates stop-loss and take-profit levels using ATR with user-defined multipliers for risk management.
• Fibonacci-Based Stops/Targets (Optional): Optionally replaces ATR-based stops/targets with Fibonacci extensions for both upside (long) and downside (short) scenarios.
• Strategy Execution & Plotting: Executes trades on buy/sell signals, sets corresponding stops/targets, and plots all relevant lines (signals, pivots, fib levels) for visual reference.
works well on low TF 2-5min. not great on larger time frames. gives a lot of signals.
If you can help me make it better and filter low quality signals please let me know
[COW] Tripple Backflip Confirmation"Im a simple man just trying to make my way in the galaxy..."
- Spock from the hit movie Spaceballs
An indicator I made to fit the strat that I and Santana_trades uses!
It uses a mix of the daily open/close ranges, daily bias for upside/downside, and the ema's for the 30 min, 60 min, and daily ranges. Configurable as all hell. Have fun!
<3 moo
RSI+StRSI+RVI+MFI+DMI+CCI+MACDH+OBV+Ichimoku Milky Way// © expert-x
// Created: 2023-12-21
// Last modified: 2025-02-14
// Version 6.0
//@version=6
////////////////////////////////////////////////////////////////////////////////////////////////////
indicator(title = 'RSI+StRSI+RVI+MFI+DMI+CCI+MACDH+OBV+Ichimoku Milky Way', format = format.price, overlay = false, precision = 2, shorttitle = 'Multi+Tool Milky Way X')
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// TOOLTIPS //////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
ENABLE_TOOLTIP = 'Включить/выключить'
ST1_ENABLE_TOOLTIP = 'Стратегия пересечения линией переворота, базовой линии'
ST2_ENABLE_TOOLTIP = 'Стратегия пересечения верховой линией 1, верховой линии 2'
TR_RT_ENABLE_TOOLTIP = 'Отключает отображенине ярлыков UP/Down Trend текущего таймфрейма'
TR_MTF_ENABLE_TOOLTIP = 'Отключает отображенине ярлыков UP/Down Trend дополнительных таймфреймов'
LAST_ENABLE_TOOLTIP = 'Удалит все ярлыки, кроме последних, по-каждому тайм-фрейму.'
TIMEFRAME_TOOLTIP = 'Выбор и активация дополнительного таймфрейма'
STYLE_TOOLTIP = 'Настройки цвета'
CCI_TOOLTIP = 'Как большинство осцилляторов, CCI был разработан, чтобы определять уровни перекупленности и перепроданности. Индикатор CCI делает это, измеряя отношение между ценой и Скользящей средней, или, если быть более точным, нормальные отклонения от этой Скользящей средней. Иными словами, CCI измеряет отклонение цены инструмента от ее среднестатистической цены. Индикатор CCI показывает, насколько текущая стоимость отклонилась от своего среднего значения. Высокие показатели говорят, что она намного выше стандартной. Низкие ― актив недооценен и вскоре станет дороже. Таким образом определяются зоны перекупленности и перепроданности, что является характерной чертой осцилляторов. CCI работает на всех таймфреймах и активах. Алгоритм прогнозирует разворот текущего тренда.'
RSI_TOOLTIP = 'RSI — это импульсный индикатор для технического трейдинга, который измеряет скорость изменения цены или данных. Увеличение импульса и рост цены указывают на активные покупки акций на рынке. При этом снижение импульса свидетельствует об увеличении давления продавцов. Кроме того, RSI позволяет трейдерам обнаружить признаки перепроданности и перекупленности рынка. Для этого цена актива оценивается по шкале от 0 до 100 за 14 периодов.'
STOCHASTIC_TOOLTIP = 'Стохастический RSI, или просто StochRSI - это индикатор технического анализа, используемый для определения того, перекуплен актив или перепродан, а также для определения текущих рыночных тенденций. Как следует из названия, StochRSI является производной от стандартного Индекса Относительной Силы (RSI) и как таковой, считается индикатором индикатора. Это тип осциллятора, означающий, что он колеблется выше и ниже центральной линии. ' + 'Впервые StochRSI был описан в 1994 году, в книге Новый Технический Трейдер Стэнли Кролла и Тушар Чанде. Она часто используется биржевыми трейдерами, но также может применяться и в других торговых аспектах, к примеру для торгов на Forex или криптовалютой. ' + 'Как работает StochRSI? Индикатор StochRSI генерируется из обычного RSI путем применения формулы Стохастического Осциллятора. Результатом является единый числовой рейтинг, который колеблется вокруг центральной линии (0,5) в диапазоне от 0 до 1. Однако существуют модифицированные версии StochRSI, которые умножают результаты на 100, поэтому значение находятся в диапазоне от 0 до 100 вместо 0 и 1. Также часто встречается 3-дневная простая скользящая средняя (SMA) вместе с линией StochRSI, которая выступает в качестве сигнала и предназначена для снижения торговых рисков. ' + 'Стандартная формула Стохастического Осциллятора учитывает цену закрытия актива, а также его самые высокие и самые низкие точки в течение определенного периода. Однако когда формула используется для расчета StochRSI, она непосредственно применяется к данным от RSI (цены не учитываются). ' + 'Stoch RSI = (Текущий RSI - Наименьший RSI)/(Наибольший RSI - Наименьший RSI) Как и в стандартном RSI, для StochRSI чаще всего используется настройка 14 периодов. 14 периодов, участвующих в расчете StochRSI, основаны на временных рамках графика. Таким образом, в то время как дневной график будет учитывать последние 14 дней (свечи), часовой график будет генерировать StochRSI на основе последних 14 часов. ' + 'Периоды могут быть установлены в днях, часах или даже минутах, и их использование значительно варьируется от трейдера к трейдеру (в зависимости от их стратегии). Количество периодов также может быть скорректировано вверх или вниз, чтобы определить долгосрочные или краткосрочные тренды. 20-периодная настройка, это еще один довольно популярный параметр для StochRSI. ' + 'Как уже упоминалось, некоторые графические шаблоны StochRSI присваивают значения в диапазоне от 0 до 100 вместо 0 до 1. На этих графиках центральная линия находится на уровне 50 вместо 0,5. Следовательно, сигнал перекупленности, который обычно возникает на уровне 0,8, будет обозначаться как 80, а сигнал перепроданности, на уровне 20, а не 0,2. Графики с настройкой от 0 до 100 могут выглядеть немного иначе, но практическая интерпретация по сути одна и та же. ' + 'Как использовать StochRSI? Индикатор StochRSI приобретает наибольшее значение вблизи верхних и нижних границ своего диапазона. Поэтому основное использование индикатора заключается в определении потенциальных точек входа и выхода, а также разворотов цен. Таким образом, значение 0,2 или ниже, указывает на то, что актив вероятнее всего перепродан, а значение 0,8 или выше предполагает, что он может быть перекуплен. ' + 'Кроме того, нахождение линий ближе к центру, также может предоставить полезную информацию относительно рыночных тенденций. Например, когда центральная линия выступает в качестве поддержки, а линии StochRSI постоянно движутся выше отметки 0,5, это может указывать на продолжение бычьего или восходящего тренда, особенно если линии начинают двигаться в направлении 0,8. Аналогично, последовательные колебания ниже 0,5 и отклонения к 0,2 указывают на нисходящий или медвежий тренд.'
MF_INDEX_TOOLTIP = 'Индикатор Money Flow Index (MFI) — это инструмент, используемый в техническом анализе для измерения давления покупки и продажи. Это делается путем анализа как цены, так и объёма. Расчет MFI генерирует значение, которое затем отображается как линия, которая перемещается в диапазоне 0-100, что делает его осциллятором. Когда MFI повышается, это указывает на увеличение покупательского давления.'
DMI_TOOLTIP = 'Что такое DMI: Индекс направленного движения (DMI) — это технический индикатор, используемый трейдерами для определения силы восходящего или нисходящего тренда на рынке. ' + 'Индекс направленного движения (DMI) — это технический индикатор, используемый трейдерами для определения силы восходящего или нисходящего тренда на рынке. Он включает в себя два индекса направления и обычно используется в тандеме с индексом среднего направления движения (ADX). Таким образом, DMI отображается в виде трех линий выше или ниже свечного графика. ' + 'Что такое DMI индикатор? DMI – индекс направленного движения – состоит из двух индексов направления: Plus Direction Indicator (также называемого индикатором положительного направления), обозначаемого DI+, и Minus Direction Indicator (также называемого индикатором отрицательного направления), обозначаемого DI-. Когда линия DI+ находится выше линии DI-, рынки находятся в бычьем тренде. И наоборот, когда линия DI- выше линии DI+, рынки находятся в медвежьем тренде. Когда линии показывают повторяющиеся пересечения — рынки находятся в нерешительности, и цены торгуются относительно стабильно. ' + 'Сами по себе индексы DMI не скажут вам слишком многого, чего вы не смогли бы понять, взглянув на стандартный свечной график. Некоторые трейдеры используют точки пересечения в качестве торгового сигнала, поскольку они указывают на разворот тренда. Однако индексы DMI также включают третью строку, называемую индексом среднего направления движения (ADX).'
ADX_TOOLTIP = 'Что такое ADX: Индекс среднего направления движения (ADX) представляет собой индикатор относительной силы направленного тренда, обозначенного DI+ и DI-. ' + 'Что такое ADX индикатор?ADX – индекс среднего направления движения – представляет собой индикатор относительной силы направленного тренда, обозначенного DI+ и DI-. Чтобы прочитать его, обратитесь к оси на диаграмме, которая показывает значение. В целом, значение ADX выше 25 указывает на то, что тренд относительно силен. Значение ниже 20 указывает на то, что тренд слабый или что рынки торгуются в боковом тренде. Также может случиться так, что рынки переживают период волатильности, и ADX не может определить четкий тренд ни в одном направлении. ' + 'Значения DMI и ADX определяются на основе диапазона ценовых движений за последние 14 торговых периодов. Существуют математические формулы, которые позволят вам самостоятельно рассчитать значения; однако это сложно и в значительной степени не нужно для большинства трейдеров. Все, что вам нужно знать, это как интерпретировать значения DMI и ADX на графике и использовать их в своих торговых сигналах. ' + 'Как использовать DMI и ADX в торговле. Вы можете видеть, что DMI и ADX представляются как один индикатор или как два отдельных индикатора, в зависимости от того, какие инструменты построения графиков вы используете. В Trading View при выборе среднего индекса направления отображается только график с линией ADX, тогда как при выборе индекса направленного движения отображается график как с линиями DI, так и с линией ADX. ' + 'Индикаторы положительного (DI+) и отрицательного (DI-) направления. Если вы планируете использовать DMI и ADX в торговле, вам понадобятся два важных индикатора. Первый — это точка, когда линии DI+ и DI- пересекаются друг с другом, что указывает на разворот тренда. ' + 'Тем не менее, вы должны быть осторожны, если линии DI+ и DI- уже пересекались несколько раз в предыдущие торговые периоды или проходят очень близко друг к другу, так как это указывает на то, что рынки не определились и ни быки, ни медведи не контролируют ситуацию. Чем дальше друг от друга находятся линии DI+ и DI-, тем сильнее индикатор тренда. ' + 'Откуда взялись DMI и ADX? Индикаторы DMI и ADX были разработаны в 1970-х годах американским техническим аналитиком Дж. Уэллсом Уайлдером, автором книги «Новые концепции технических торговых систем». Он изобрел несколько технических индикаторов, которые сейчас используются трейдерами по всему миру, в том числе индекс относительной силы и Parabolic SAR.'
RVI_TOOLTIP = 'Индекс относительной волатильности - RVI. Технический индикатор RVI был разработан Дональдом Дорси в 1993 году, а затем описан в журнале Technical Analysis of Stocks and Commodities. В 1995 году индикатор был преобразован автором, и его обновленная версия была использована для анализа. По словам Дорси, индикатор RVI не является независимым инструментом технического анализа и может использоваться либо в качестве фильтра для других индикаторов, либо в качестве инструмента для указания на намерения, но не на возможности реализации ценовых моделей. ' + 'Торговое использование. ' + 'Главное преимущество RVI заключается в том, что он основан на индексе RSI и учитывает все уровни диверсификации, которые могут быть опущены RSI. Тем не менее, RVI является изменчивым индикатором, но не классическим осциллятором, поэтому неразумно использовать его независимо. Как следствие, лучше сочетать сигналы RVI с осцилляторными сигналами технического анализа, например, индикатором RSI. ' + 'В случае, если индикатор RSI попадет в зону перепроданности, преодолевая 70% вместе с RVI, мы получаем мощный сигнал о том, что повышение цен скоро закончится и начнется снижение. ' + 'Кроме того, если и индикаторы RSI, и RVI опадают ниже уровня 30%, другими словами, попадают в зону перекупленности, необходимо быть готовым к росту цен. В соответствии с этим лучше использовать комбинацию этих двух показателей, чем применять их самостоятельно. ' + 'Когда RSI составляет более 70% или менее 30%, но RVI не подтверждает эти сигналы, лучше подождать, пока оба из них не покажут похожую картину, прежде чем открыть позицию. ' + 'Другим вариантом применения RVI является выявление расхождений и конвергенции с ценой. Если цена идет вверх, пока индекс падает, это указывает на то, что цена скоро снизится (случай расхождения). ' + 'Противоположная ситуация также верна для жизни: индекс падает, в то время как цена растет, что свидетельствует об ускорении цены (случай конвергенции). ' + 'Формирование этих сигналов более актуально, когда RVI находится в зоне перекупленной или перепроданной. Но даже если индекс RVI попадет в нейтральную зону (между 30%-70%), сигналы расхождения/конвергенции также будут показательными. ' + 'Учитывая, что RVI рассматривает больший масштаб параметров, чем индекс RSI, сигналы, полученные с помощью RVI, будут намного лучше.'
forceoverlay_tooltip = 'Данный параметр, отобразит этикетки Лонг/Шорт непосредственно на основном графике'
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// GROUPS ///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
cci_set_group = 'CCI setup'
components = 'enable/disable components'
rd_algorithm_1_group = 'Long/Short Algorithm "CCI"'
rd_algorithm_2_group = 'Long/Short Algorithm "DMI & ADX"'
rd_algorithm_3_group = 'Long/Short Algorithm "STRSI"'
rd_algorithm_4_group = 'Long/Short Algorithm "EMA GC/DC"'
rd_algorithm_5_group = 'Long/Short Algorithm "MACD HISTOGRAM"'
rd_algorithm_6_group = 'Long/Short Algorithm "CCI"'
rd_algorithm_7_group = 'Long/Short Algorithm "OBV"'
rd_close_algorithm_group = 'Long/Short Close position algorithm'
rd_long_short_group = 'Long/Short strategy modul'
rd_ma_set = 'MA Settings'
rd_macd_group = 'MACD HISTOGRAM'
rd_mfi_set_group = 'Money Flow Index (MFI) setup'
rvi_group = 'Relative Volatility Index'
trend_group = 'Ichimoku UP/Down Trend'
// Рассчитываем нулевую линию
cci_zero_line = 50
dmiadx_zero_line = 75
macd_zero_line = 0
mfi_zero_line = 100
rsi_zero_line = 50
rvi_zero_line = 50
strsi_zero_line = 100
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// COMPONENTS ////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
show_trend_01_module_input = input.bool(true, title = 'Show Ichimoku trending strategy 1', group = components, tooltip = ST1_ENABLE_TOOLTIP)
show_trend_02_module_input = input.bool(false, title = 'Show Ichimoku trending strategy 2', group = components, tooltip = ST2_ENABLE_TOOLTIP)
show_rsi_modul_input = input.bool(true, title = 'Show "RSI" modul', group = components, tooltip = RSI_TOOLTIP)
show_rsi_ma_plot_input = input.bool(true, title = 'Show "RSI" smoothing line', group = components, tooltip = RSI_TOOLTIP)
show_rsi_divergence = input.bool(false, title = 'Show Divergence', group = components, tooltip = RSI_TOOLTIP)
show_stoc_rsi_modul_input = input.bool(true, title = 'Show "Stochastic RSI" modul', group = components, tooltip = STOCHASTIC_TOOLTIP)
show_rvi_modul_input = input.bool(false, title = 'Show "RVI" modul', group = components, tooltip = RVI_TOOLTIP)
show_rvi_ma_plot_input = input.bool(false, title = 'Show "RVI" smoothing line', group = components, tooltip = RVI_TOOLTIP)
show_rd_modul_input = input.bool(false, title = 'Show "DMI & ADX" modul', group = components, tooltip = DMI_TOOLTIP)
show_mfi_modul_input = input.bool(false, title = 'Show "MFI" modul', group = components, tooltip = MF_INDEX_TOOLTIP)
show_cci_modul_input = input.bool(true, title = 'Show "CCI" modul', group = components, tooltip = CCI_TOOLTIP)
show_cci_ma_plot_input = input.bool(true, title = 'Show "CCI" smoothing line', group = components, tooltip = CCI_TOOLTIP)
show_macd_histo_modul_input = input.bool(true, title = 'Show "MACD Histogram" modul', group = components, tooltip = ENABLE_TOOLTIP)
show_long_short_modul_input = input.bool(true, title = 'Show "Long/Short" strategy modul', group = components, tooltip = ENABLE_TOOLTIP)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// Ichimoku Trend X /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
conversionPeriods = input.int(13, minval = 1, title = 'Длина линии переворота', group = trend_group)
basePeriods = input.int(60, minval = 1, title = 'Длина линии стандарта', group = trend_group)
laggingSpan2Periods = input.int(60, minval = 1, title = 'Длина верховой линии 2', group = trend_group)
displacement = input.int(21, minval = 1, title = 'Опаздывающая линия', group = trend_group)
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
base_offset = displacement - 1
contr_offset = -displacement + 1
////////////////////////////////////////////////////////////////////////////////////////////////////
plot(conversionLine, color = color.new(#2962FF, 0), title = 'Conversion Line', linewidth = 3, style = plot.style_line, display = display.none, force_overlay = true)
plot(baseLine, color = color.new(#B71C1C, 0), title = 'Base Line', linewidth = 3, style = plot.style_line, display = display.none, force_overlay = true)
plot(close, offset = contr_offset, color = #43A047, title = 'Lagging Span Line', linewidth = 3, style = plot.style_line, display = display.none, force_overlay = true)
p1 = plot(leadLine1, offset = base_offset, color = #A5D6A7, title = 'Leading Span Line 1', linewidth = 3, style = plot.style_line, display = display.none, force_overlay = true)
p2 = plot(leadLine2, offset = base_offset, color = #EF9A9A, title = 'Leading Span Line 2', linewidth = 3, style = plot.style_line, display = display.none, force_overlay = true)
kumo_cloud_upper_line = leadLine1 > leadLine2 ? leadLine1 : leadLine2
kumo_cloud_lower_line = leadLine1 < leadLine2 ? leadLine1 : leadLine2
plot(kumo_cloud_upper_line, offset = base_offset, title = 'Kumo Cloud Upper Line', force_overlay = true)
plot(kumo_cloud_lower_line, offset = base_offset, title = 'Kumo Cloud Lower Line', force_overlay = true)
fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 75) : color.rgb(244, 67, 54, 75))
downtrend_01 = ta.crossover(baseLine, conversionLine)
uptrend_01 = ta.crossunder(baseLine, conversionLine)
downtrend_02 = ta.crossover(leadLine1, leadLine2)
uptrend_02 = ta.crossunder(leadLine1, leadLine2)
uptrend_01_label_color_input = input.color(color.new(#1b5e20, 0), title = 'label uptrend_01', inline = 'trend_color1', group = trend_group, tooltip = STYLE_TOOLTIP)
downtrend_01_label_color_input = input.color(color.new(#e65100, 0), title = 'downtrend_01', inline = 'trend_color1', group = trend_group, tooltip = STYLE_TOOLTIP)
uptrend_02_label_color_input = input.color(color.new(#1b5e20, 0), title = 'label uptrend_02', inline = 'trend_color2', group = trend_group, tooltip = STYLE_TOOLTIP)
downtrend_02_label_color_input = input.color(color.new(#e65100, 0), title = 'downtrend_02', inline = 'trend_color2', group = trend_group, tooltip = STYLE_TOOLTIP)
label_textcolor_input = input.color(color.new(color.white, 5), title = 'label font color ', group = trend_group, tooltip = STYLE_TOOLTIP)
only_last_label = input.bool(false, title = 'Show only last label', group = trend_group, tooltip = LAST_ENABLE_TOOLTIP)
////////////////////////////////////////////////////////////////////////////////////////////////////
if show_trend_01_module_input ? downtrend_01 : bool(na)
label_downtrend_01 = label.new(x = na, y = na, text = '', force_overlay = true)
label.set_xy(label_downtrend_01, x = bar_index, y = low)
label.set_text(label_downtrend_01, text = 'DownTrend1⬇ Ichimoku ' + 'TF' + str.tostring(timeframe.period))
label.set_yloc(label_downtrend_01, yloc = yloc.abovebar)
label.set_color(label_downtrend_01, color = downtrend_01_label_color_input)
label.set_style(label_downtrend_01, style = label.style_label_down)
label.set_textcolor(label_downtrend_01, textcolor = label_textcolor_input)
label.set_size(label_downtrend_01, size = size.small)
label.set_textalign(label_downtrend_01, textalign = text.align_center)
label.set_tooltip(label_downtrend_01, tooltip = 'Down Trend')
if only_last_label
label.delete(label_downtrend_01 )
else
na
if show_trend_01_module_input ? uptrend_01 : bool(na)
label_uptrend_01 = label.new(x = na, y = na, text = '', force_overlay = true)
label.set_xy(label_uptrend_01, x = bar_index, y = low)
label.set_text(label_uptrend_01, text = 'UpTrend1⬆ Ichimoku ' + 'TF' + str.tostring(timeframe.period))
label.set_yloc(label_uptrend_01, yloc = yloc.belowbar)
label.set_color(label_uptrend_01, color = uptrend_01_label_color_input)
label.set_style(label_uptrend_01, style = label.style_label_up)
label.set_textcolor(label_uptrend_01, textcolor = label_textcolor_input)
label.set_size(label_uptrend_01, size = size.small)
label.set_textalign(label_uptrend_01, textalign = text.align_center)
label.set_tooltip(label_uptrend_01, tooltip = 'Up Trend')
if only_last_label
label.delete(label_uptrend_01 )
else
na
////////////////////////////////////////////////////////////////////////////////////////////////////
if show_trend_02_module_input ? downtrend_02 : bool(na) // and kumo_cloud_lower_line > open
label_downtrend_02 = label.new(x = na, y = na, text = '', force_overlay = true)
label.set_xy(label_downtrend_02, x = bar_index + base_offset, y = low)
label.set_text(label_downtrend_02, text = 'DownTrend2⬇ Ichimoku ' + 'TF' + str.tostring(timeframe.period))
label.set_yloc(label_downtrend_02, yloc = yloc.abovebar)
label.set_color(label_downtrend_02, color = downtrend_02_label_color_input)
label.set_style(label_downtrend_02, style = label.style_label_down)
label.set_textcolor(label_downtrend_02, textcolor = label_textcolor_input)
label.set_size(label_downtrend_02, size = size.small)
label.set_textalign(label_downtrend_02, textalign = text.align_center)
label.set_tooltip(label_downtrend_02, tooltip = 'Down Trend')
if only_last_label
label.delete(label_downtrend_02 )
else
na
if show_trend_02_module_input ? uptrend_02 : bool(na) // and kumo_cloud_upper_line < open
label_uptrend_02 = label.new(x = na, y = na, text = '', force_overlay = true)
label.set_xy(label_uptrend_02, x = bar_index + base_offset, y = low)
label.set_text(label_uptrend_02, text = 'UpTrend2⬆ Ichimoku ' + 'TF' + str.tostring(timeframe.period))
label.set_yloc(label_uptrend_02, yloc = yloc.belowbar)
label.set_color(label_uptrend_02, color = uptrend_02_label_color_input)
label.set_style(label_uptrend_02, style = label.style_label_up)
label.set_textcolor(label_uptrend_02, textcolor = label_textcolor_input)
label.set_size(label_uptrend_02, size = size.small)
label.set_textalign(label_uptrend_02, textalign = text.align_center)
label.set_tooltip(label_uptrend_02, tooltip = 'Up Trend')
if only_last_label
label.delete(label_uptrend_02 )
else
na
////////////////////////////////////////////////////////////////////////////////////////////////////
highUsePivot = fixnan(ta.pivothigh(15, 15) )
lowUsePivot = fixnan(ta.pivotlow(15, 15) )
volumeThresh = 20
shortVolume = ta.ema(volume, 5)
longVolume = ta.ema(volume, 10)
osc = 100 * (shortVolume - longVolume) / longVolume
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// LONG/SHORT INPUT ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_consider_algo_1_input = input.bool(false, title = 'Activate CCI algorithm', group = rd_algorithm_1_group, tooltip = ENABLE_TOOLTIP)
rd_factor_rsi_open_long_algo_1_input = input.int(42, title = 'Factor RSI open Long', group = rd_algorithm_1_group, minval = 20, maxval = 50)
rd_factor_rsi_open_short_algo_1_input = input.int(58, title = 'Factor RSI open Short', group = rd_algorithm_1_group, minval = 51, maxval = 80)
cci_length = input.int(20, title = 'Length', minval = 1, group = rd_algorithm_1_group)
cci_src = input.source(hlc3, title = 'Source', group = rd_algorithm_1_group)
cci_plot_color_input = input.color(color.new(#4caf50, 0), title = 'CCI line color', group = rd_algorithm_1_group, tooltip = STYLE_TOOLTIP)
cci_smoothing_plot_color_input = input.color(color.new(#3179f5, 0), title = 'CCI smoothing line color', group = rd_algorithm_1_group, tooltip = STYLE_TOOLTIP)
cci_ma = ta.sma(cci_src, cci_length)
cci = (cci_src - cci_ma) / (0.15 * ta.dev(cci_src, cci_length)) // fill(cci_band1, cci_band0, color=color.rgb(33, 150, 243, 90), title="Background")
cci_ma(source, cci_length, type) =>
switch type
'SMA' => ta.sma(source, cci_length)
'EMA' => ta.ema(source, cci_length)
'SMMA (RMA)' => ta.rma(source, cci_length)
'WMA' => ta.wma(source, cci_length)
'VWMA' => ta.vwma(source, cci_length)
cci_typeMA = input.string(defval = 'SMMA (RMA)', title = 'Method', options = , group = rd_algorithm_1_group)
cci_smoothingLength = input.int(5, title = 'Length', minval = 1, maxval = 100, group = rd_algorithm_1_group)
cci_smoothingLine = cci_ma(cci, cci_smoothingLength, cci_typeMA)
cci_cross = ta.cross(cci, cci_smoothingLine)
plot(show_cci_modul_input ? cci + rsi_zero_line - cci_zero_line : na, color = cci_plot_color_input, title = 'CCI', linewidth = 3)
plot(show_cci_modul_input ? show_cci_ma_plot_input ? cci_smoothingLine + rsi_zero_line - cci_zero_line : na : na, color = cci_smoothing_plot_color_input, title = 'CCI Smoothing Line', linewidth = 3) // , display=display.none
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_consider_algo_2_input = input.bool(false, title = 'Activate RSI algorithm', group = rd_algorithm_2_group, tooltip = ENABLE_TOOLTIP)
rd_factor_rsi_open_long_algo_2_input = input.int(30, title = 'Factor RSI open Long (1 - 50)', group = rd_algorithm_2_group, minval = 1, maxval = 50)
rd_factor_rsi_open_short_algo_2_input = input.int(70, title = 'Factor RSI open Short (50 - 100)', group = rd_algorithm_2_group, minval = 50, maxval = 100)
rd_ma(source, length, type) =>
switch type
'SMA' => ta.sma(source, length)
'Bollinger Bands' => ta.sma(source, length)
'EMA' => ta.ema(source, length)
'SMMA (RMA)' => ta.rma(source, length)
'WMA' => ta.wma(source, length)
'VWMA' => ta.vwma(source, length)
rd_rsi_length_input = input.int(19, title = 'RSI Length', group = rd_algorithm_2_group, minval = 1)
rd_rsi_plot_color_input = input.color(color.new(#b2b5be, 65), title = 'RSI plot color', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_rsi_source_input = input.source(close, title = 'Source', group = rd_algorithm_2_group)
rd_ma_type_input = input.string('Bollinger Bands', title = 'Method', group = rd_algorithm_2_group, options = )
rd_ma_length_input = input.int(5, title = 'MA Length', group = rd_algorithm_2_group)
rd_bb_mult_input = input.float(4.0, title = 'BB StdDev', group = rd_algorithm_2_group, minval = 0.001, maxval = 50)
rd_ma_plot_color_input = input.color(color.new(#787b86, 30), title = 'RSI-based MA plot color', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_RSI_Highest_Band_color = input.color(color.new(#ff5252, 30), title = 'RSI highest band', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_RSI_Upper_Band_color = input.color(color.new(color.white, 25), title = 'RSI upper band', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_MID_line_Band_color = input.color(color.new(color.white, 75), title = 'RSI middle band', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_RSI_Lower_Band_color = input.color(color.new(color.white, 25), title = 'RSI lower band', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_RSI_lowest_Band_color = input.color(color.new(color.green, 30), title = 'RSI lowest band', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_Fill_Color = input.color(color.new(#311b92, 70), title = 'RSI Background Fill', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
rd_BB_Fill_Color = input.color(color.new(#5b9cf6, 75), title = 'Bollinger Bands Background Fill', group = rd_algorithm_2_group, tooltip = STYLE_TOOLTIP)
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_consider_algo_3_input = input.bool(false, title = 'Activate STRSI algorithm', group = rd_algorithm_3_group, tooltip = ENABLE_TOOLTIP)
rd_factor_strsi_open_long_algo_3_input = input.int(10, title = 'Factor ST RSI open Long (1 - 50)', group = rd_algorithm_3_group, minval = 1, maxval = 100)
rd_factor_strsi_open_short_algo_3_input = input.int(90, title = 'Factor ST RSI open Short(50 - 100)', group = rd_algorithm_3_group, minval = 1, maxval = 100)
rd_strsi_smooth_k_input = input.int(4, title = 'K', group = rd_algorithm_3_group, minval = 1)
rd_strsi_smoot_d_input = input.int(3, title = 'D', group = rd_algorithm_3_group, minval = 1)
//rd_strsi_length_rsi_input = input.int(19, title = 'RSI Length', group = rd_algorithm_3_group, minval = 1)
rd_strsi_length_stoch_input = input.int(15, title = 'Stochastic Length', group = rd_algorithm_3_group, minval = 1)
//rd_strsi_src_input = input(close, title = 'RSI Source', group = rd_algorithm_3_group)
rd_strsi_plot_k_color_input = input.color(color.new(#2962FF, 5), title = 'Stochastic RSI(K) plot color', group = rd_algorithm_3_group, tooltip = STYLE_TOOLTIP)
rd_strsi_plot_d_color_input = input.color(color.new(#FF6D00, 5), title = 'Stochastic RSI(D) plot color', group = rd_algorithm_3_group, tooltip = STYLE_TOOLTIP)
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_consider_algo_4_input = input.bool(false, title = 'Activate DMI & ADX algorithm', group = rd_algorithm_4_group, tooltip = ENABLE_TOOLTIP)
rd_factor_rsi_open_long_algo_4_input = input.int(35, title = 'Factor RSI open Long', group = rd_algorithm_4_group, minval = 1, maxval = 100)
rd_factor_rsi_open_short_algo_4_input = input.int(65, title = 'Factor RSI open Short', group = rd_algorithm_4_group, minval = 1, maxval = 100)
dmi_lensig = 19 //input.int(19, title = 'ADX Smoothing', group = rd_algorithm_4_group, minval = 1, maxval = 50) //14
dmi_len = 15 //input.int(15, minval=1, title = 'DI Length', group = rd_algorithm_4_group) //14
dmi_plot_adx_color_input = input.color(color.new(color.white, 10), title = 'ADX plot color', group = rd_algorithm_4_group, tooltip = STYLE_TOOLTIP) //#d1d4dc
dmi_plot_di_plus_color_input = input.color(color.new(#388e3c, 0), title = 'DI + plot color', group = rd_algorithm_4_group, tooltip = STYLE_TOOLTIP)
dmi_plot_di_minus_color_input = input.color(color.new(#f23645, 0), title = 'DI - plot color', group = rd_algorithm_4_group, tooltip = STYLE_TOOLTIP)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// MACD HISTOGRAM ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_consider_algo_5_input = input.bool(true, title = 'Activate MACD HISTOGRAM algorithm', group = rd_algorithm_5_group, tooltip = ENABLE_TOOLTIP)
rd_strsi_smooth_ls_input = input.int(15, title = 'K', group = rd_algorithm_5_group, minval = 1)
rd_factor_strsi_open_long_algo_5_input = input.int(37, title = 'Factor ST RSI open Long (1 - 50)', group = rd_algorithm_5_group, minval = 1, maxval = 100)
rd_factor_strsi_open_short_algo_5_input = input.int(63, title = 'Factor ST RSI open Short(50 - 100)', group = rd_algorithm_5_group, minval = 1, maxval = 100)
macd_fastlength = input.int(12, title = 'MACD fast length', group = rd_algorithm_5_group, minval = 1)
macd_slowlength = input.int(26, title = 'MACD slow length', group = rd_algorithm_5_group, minval = 1)
macd_signallength = input.int(9, title = 'MACD signal length', group = rd_algorithm_5_group, minval = 1)
macd_source = close
macd_histo_color_1 = color.new(color.lime, 70)
macd_histo_color_2 = color.new(color.green, 70)
macd_histo_color_3 = color.new(color.maroon, 70)
macd_histo_color_4 = color.new(color.red, 70)
macd_fastma = ta.ema(macd_source, macd_fastlength)
macd_slowma = ta.ema(macd_source, macd_slowlength)
macd_line = macd_fastma - macd_slowma
macd_signal = ta.ema(macd_line, macd_signallength)
macd_histo = macd_line - macd_signal
macd_plotcolor = if macd_histo > 0
macd_histo > macd_histo ? macd_histo_color_1 : macd_histo_color_2
else
macd_histo < macd_histo ? macd_histo_color_3 : macd_histo_color_4
// Определяем значения для верхней и нижней границы RSI
rsi_upper_bound = 100
rsi_lower_bound = 0
// Рассчитываем значения MACD гистограммы, ограничивая их между границами RSI
macd_histo_bounded = macd_histo
if macd_histo > 0
macd_histo_bounded := math.min(macd_histo, rsi_upper_bound - rsi_zero_line + macd_zero_line)
macd_histo_bounded
else
macd_histo_bounded := math.max(macd_histo, rsi_lower_bound - rsi_zero_line + macd_zero_line)
macd_histo_bounded
plot(show_macd_histo_modul_input ? macd_histo_bounded : na, title = 'MACD', color = macd_plotcolor, style = plot.style_area)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// OBV INPUTS ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// obv_plot_color_input = input.color(color.new(#2962FF, 5), title = 'OBV line color', group = rd_algorithm_6_group, tooltip = STYLE_TOOLTIP) //rd_obv_group
// obv_smoothing_plot_color_input = input.color(color.new(#f37f20, 5), title = 'OBV smoothing line color', group = rd_algorithm_6_group, tooltip = STYLE_TOOLTIP)
rd_consider_algo_6_input = input.bool(true, title = 'Activate OBV algorithm', group = rd_algorithm_6_group, tooltip = ENABLE_TOOLTIP)
rd_factor_rsi_open_long_algo_6_input = input.int(42, title = 'Factor RSI open Long', group = rd_algorithm_6_group, minval = 1, maxval = 100)
rd_factor_rsi_open_short_algo_6_input = input.int(58, title = 'Factor RSI open Short', group = rd_algorithm_6_group, minval = 1, maxval = 100)
obv_type_ma = input.string(defval = 'SMMA (RMA)', title = 'OBV smoothing method', options = , group = rd_algorithm_6_group)
obv_smoothing_length = input.int(10, title = 'OBV smoothing Length', group = rd_algorithm_6_group, minval = 1, maxval = 100)
obv_src = input.source(close, title = 'Source', group = rd_algorithm_6_group)
var obv_cumvol = 0.
obv_cumvol := obv_cumvol + nz(volume)
if obv_cumvol == 0
runtime.error('Поставщик данных не предоставляет объем.')
obv = ta.cum(math.sign(ta.change(obv_src)) * volume)
obv_ma(source, length, type) =>
switch type
'SMA' => ta.sma(source, length)
'EMA' => ta.ema(source, length)
'SMMA (RMA)' => ta.rma(source, length)
'WMA' => ta.wma(source, length)
'VWMA' => ta.vwma(source, length)
obv_smoothing_line = obv_ma(obv, obv_smoothing_length, obv_type_ma)
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_OpenLong_label_color_input = input.color(color.new(#1b5e20, 0), title = 'Open Long Label color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_OpenShort_label_color_input = input.color(color.new(#e65100, 10), title = 'Open Short Label color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_Openlabel_textcolor_input = input.color(color.new(color.white, 10), title = 'Open Label font color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_CloseLong_label_color_input = input.color(color.new(#1b5e20, 0), title = 'Close Long Label color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_CloseShort_label_color_input = input.color(color.new(#e65100, 0), title = 'Close Short Label color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_Closelabel_textcolor_input = input.color(color.new(color.white, 20), title = 'Close Label font color', group = rd_long_short_group, tooltip = STYLE_TOOLTIP)
rd_OpenLong_label_txt = 'LONG'
rd_OpenShort_label_txt = 'SHORT'
rd_CloseLong_label_txt = 'SHORT'
rd_CloseShort_label_txt = 'LONG'
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// MFI INPUTS ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_mfi_length = input.int(19, title = 'MFI Length', group = rd_mfi_set_group, minval = 1, maxval = 2000)
rd_mfi_plot_color = input.color(color.new(#9598a1, 10), title = 'MFI plot color', group = rd_mfi_set_group, tooltip = STYLE_TOOLTIP)
rd_mfi_source_input = input.source(hlc3, title = 'Source', group = rd_mfi_set_group)
rd_mfi_src = hlc3
rd_mfi_mf = ta.mfi(rd_mfi_source_input, rd_mfi_length)
plot(show_mfi_modul_input ? rd_mfi_mf + rsi_zero_line - mfi_zero_line : na, title = 'MFI', color = rd_mfi_plot_color, linewidth = 1, style = plot.style_histogram)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// RSI //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_up = ta.rma(math.max(ta.change(rd_rsi_source_input), 0), rd_rsi_length_input)
rd_down = ta.rma(-math.min(ta.change(rd_rsi_source_input), 0), rd_rsi_length_input)
rd_rsi = rd_down == 0 ? 100 : rd_up == 0 ? 0 : 100 - 100 / (1 + rd_up / rd_down)
rd_rsi_ma = rd_ma(rd_rsi, rd_ma_length_input, rd_ma_type_input)
rd_is_BB = rd_ma_type_input == 'Bollinger Bands'
rd_rsi_plot = plot(show_rsi_modul_input ? rd_rsi - rsi_zero_line : na, title = 'RSI', color = rd_rsi_plot_color_input, linewidth = 2, style = plot.style_columns) //style = plot.style_cross
rd_MA_Plot = plot(show_rsi_modul_input ? show_rsi_ma_plot_input ? rd_rsi_ma - rsi_zero_line : na : na, title = 'RSI Smoothing Line', color = rd_ma_plot_color_input, linewidth = 2)
rd_RSI_Highest_Band = hline(90 - rsi_zero_line, title = '', color = rd_RSI_Highest_Band_color, linewidth = 1, linestyle = hline.style_solid, editable = false, display = display.none)
rd_RSI_Upper_Band = hline(70 - rsi_zero_line, title = '', color = rd_RSI_Upper_Band_color, linewidth = 1, linestyle = hline.style_dotted, editable = false, display = display.none)
rd_MID_line_Band = hline(50 - rsi_zero_line, title = '', color = rd_MID_line_Band_color, linewidth = 1, linestyle = hline.style_solid, editable = false, display = display.none)
rd_RSI_Lower_Band = hline(30 - rsi_zero_line, title = '', color = rd_RSI_Lower_Band_color, linewidth = 1, linestyle = hline.style_dotted, editable = false, display = display.none)
rd_RSI_lowest_Band = hline(10 - rsi_zero_line, title = '', color = rd_RSI_lowest_Band_color, linewidth = 1, linestyle = hline.style_solid, editable = false, display = display.none)
fill(rd_RSI_Upper_Band, rd_RSI_Lower_Band, color = rd_Fill_Color, title = 'RSI Background Fill', fillgaps = true, editable = false)
rd_BB_Upper_Band = plot(show_rsi_modul_input and rd_is_BB ? show_rsi_ma_plot_input ? rd_rsi_ma - rsi_zero_line + ta.stdev(rd_rsi, rd_ma_length_input) * rd_bb_mult_input : na : na, title = 'RSI Upper Bollinger Band', color = color.new(#90bff9, 0), editable = false)
rd_BB_Lower_Band = plot(show_rsi_modul_input and rd_is_BB ? show_rsi_ma_plot_input ? rd_rsi_ma - rsi_zero_line - ta.stdev(rd_rsi, rd_ma_length_input) * rd_bb_mult_input : na : na, title = 'RSI Lower Bollinger Band', color = color.new(#90bff9, 0), editable = false)
fill(rd_BB_Upper_Band, rd_BB_Lower_Band, color = rd_is_BB ? show_rsi_ma_plot_input ? rd_BB_Fill_Color : na : na, title = 'RSI Bollinger Bands Background Fill', editable = false, fillgaps = true)
rd_MID_Line_Plot = plot(50 - rsi_zero_line, color = na, title = 'RSI Middle Bollinger Band', editable = false, display = display.none)
fill(rd_rsi_plot, rd_MID_Line_Plot, 100 - rsi_zero_line, 70 - rsi_zero_line, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = 'RSI Overbought Gradient Fill')
fill(rd_rsi_plot, rd_MID_Line_Plot, 30 - rsi_zero_line, 0 - rsi_zero_line, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = 'RSI Oversold Gradient Fill')
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// STOCHASTIC RSI ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//rd_rsi = ta.rsi(rd_strsi_src_input, rd_strsi_length_rsi_input)
rd_strsi_k = ta.sma(ta.stoch(rd_rsi, rd_rsi, rd_rsi, rd_strsi_length_stoch_input), rd_strsi_smooth_k_input)
rd_strsi_d = ta.sma(rd_strsi_k, rd_strsi_smoot_d_input)
rd_strsi_macdh = ta.sma(ta.stoch(rd_rsi, rd_rsi, rd_rsi, rd_strsi_length_stoch_input), rd_strsi_smooth_ls_input)
plot(show_stoc_rsi_modul_input ? rd_strsi_k + rsi_zero_line - strsi_zero_line : na, title = 'STRSI K', color = rd_strsi_plot_k_color_input, linewidth = 1)
plot(show_stoc_rsi_modul_input ? rd_strsi_d + rsi_zero_line - strsi_zero_line : na, title = 'STRSI D', color = rd_strsi_plot_d_color_input, linewidth = 1)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// RELATIVE VOLATILITY INDEX (RVI) INPUTS ///////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rvi_plot_color_input = input.color(color.new(#b2b5be, 15), title = 'RVI plot color', group = rvi_group, tooltip = STYLE_TOOLTIP)
rvi_ma_plot_color_input = input.color(color.new(#5b9cf6, 15), title = 'RVI Smoothing Line color', group = rvi_group, tooltip = STYLE_TOOLTIP)
rvi_length = input.int(10, minval = 1, group = rvi_group)
rvi_offset = input.int(0, 'Offset', minval = -500, maxval = 500, group = rvi_group)
rvi_matypeinput = input.string('SMA', title = 'MA Type', options = , group = rvi_group)
rvi_marvi_lengthinput = input.int(14, title = 'RVI MA Length', group = rvi_group)
rvi_bbmultinput = input.float(2.0, minval = 0.001, maxval = 50, title = 'BB StdDev', group = rvi_group)
rvi_src = input.source(close, 'Source', group = rvi_group)
rvi_len = input.int(14, title = 'RVI lenght', group = rvi_group)
rvi_stddev = ta.stdev(rvi_src, rvi_length)
rvi_upper = ta.ema(ta.change(rvi_src) <= 0 ? 0 : rvi_stddev, rvi_len)
rvi_lower = ta.ema(ta.change(rvi_src) > 0 ? 0 : rvi_stddev, rvi_len)
rvi = rvi_upper / (rvi_upper + rvi_lower) * 100
ma(source, rvi_length, type) =>
switch type
'SMA' =>
'Bollinger Bands' =>
= ta.bb(source, rvi_length, rvi_bbmultinput)
'EMA' =>
'SMMA (RMA)' =>
'WMA' =>
'VWMA' =>
= ma(rvi, rvi_marvi_lengthinput, rvi_matypeinput)
// rvi_h0 = hline(80, "Upper Band", color=#787B86)
// hline(50, "Middle Band", color=color.new(#787B86, 50))
// rvi_h1 = hline(20, "Lower Band", color=#787B86)
// fill(rvi_h0, rvi_h1, color=color.rgb(126, 87, 194, 90), title="Background")
plot(show_rvi_modul_input ? rvi - rvi_zero_line : na, title = 'RVI', color = rvi_plot_color_input, offset = rvi_offset, linewidth = 1, style = plot.style_stepline)
plot(show_rvi_modul_input ? show_rvi_ma_plot_input ? rviMA - rvi_zero_line : na : na, title = 'RVI Smoothing Line', color = rvi_ma_plot_color_input, offset = rvi_offset, linewidth = 1)
rvi_bbupper = plot(show_rvi_modul_input ? highValue - rvi_zero_line : na, title = 'RVI Upper Bollinger Band', color = color.green)
rvi_bblower = plot(show_rvi_modul_input ? lowValue - rvi_zero_line : na, title = 'RVI Lower Bollinger Band', color = color.green)
fill(rvi_bbupper, rvi_bblower, color = color.new(color.green, 90), title = 'RVI Bollinger Bands Background Fill')
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// DIVERGENCE ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_Lookback_Right = 5
rd_Lookback_Left = 5
rd_Range_Upper = 60
rd_Range_Lower = 5
rd_Bear_Color = color.new(#e65100, 0)
rd_Bull_Color = color.new(#1b5e20, 0)
rd_Text_Color = color.new(color.white, 0)
rd_None_Color = color.new(color.white, 100)
rd_PL_Found = na(ta.pivotlow(rd_rsi, rd_Lookback_Left, rd_Lookback_Right)) ? false : true
rd_PH_Found = na(ta.pivothigh(rd_rsi, rd_Lookback_Left, rd_Lookback_Right)) ? false : true
_inRange(cond) =>
rd_Bars = ta.barssince(cond == true)
rd_Range_Lower <= rd_Bars and rd_Bars <= rd_Range_Upper
/////////////////////////////////////////// REGULAR BULLISH
/////////////////////////////////////////// RSI: HIGHER LOW
rd_RSI_HL = rd_rsi > ta.valuewhen(rd_PL_Found, rd_rsi , 1) and _inRange(rd_PL_Found )
// Price: Lower Low
rd_PriCeLL = low < ta.valuewhen(rd_PL_Found, low , 1)
rd_bull_cond_alert = rd_PriCeLL and rd_RSI_HL and rd_PL_Found
rd_Bull_Cond = show_rsi_divergence and rd_bull_cond_alert
plot(show_rsi_modul_input and rd_PL_Found ? rd_rsi - rsi_zero_line : na, offset = -rd_Lookback_Right, title = 'Regular Bullish', linewidth = 2, force_overlay = true, color = rd_Bull_Cond ? rd_Bull_Color : rd_None_Color)
plotshape(show_rsi_modul_input and rd_Bull_Cond ? rd_rsi - rsi_zero_line : na, offset = -rd_Lookback_Right, title = 'Regular Bullish Label', text = 'BULLS', style = shape.labelup, location = location.belowbar, force_overlay = true, color = rd_Bull_Color, textcolor = rd_Text_Color, display = display.pane)
///////////////////////////////////////////// REGULAR BEARISH
///////////////////////////////////////////// RSI: LOWER HIGH
rd_RSI_LH = rd_rsi < ta.valuewhen(rd_PH_Found, rd_rsi , 1) and _inRange(rd_PH_Found )
//////////////////////////////////////////// PRICE: HIGHER HIGH
priceHH = high > ta.valuewhen(rd_PH_Found, high , 1)
rd_bearcondalert = priceHH and rd_RSI_LH and rd_PH_Found
rd_bearCond = show_rsi_divergence and rd_bearcondalert
plot(show_rsi_modul_input and rd_PH_Found ? rd_rsi - rsi_zero_line : na, offset = -rd_Lookback_Right, title = 'Regular Bearish', linewidth = 2, force_overlay = true, color = rd_bearCond ? rd_Bear_Color : rd_None_Color)
plotshape(show_rsi_modul_input and rd_bearCond ? rd_rsi - rsi_zero_line : na, offset = -rd_Lookback_Right, title = 'Regular Bearish Label', text = 'BEARS', style = shape.labeldown, location = location.abovebar, force_overlay = true, color = rd_Bear_Color, textcolor = rd_Text_Color, display = display.pane)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// DIRECTIONAL MOVEMENT INDEX /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
dmi_up = ta.change(high)
dmi_down = -ta.change(low)
dmi_plusDM = na(dmi_up) ? na : dmi_up > dmi_down and dmi_up > 0 ? dmi_up : 0
dmi_minusDM = na(dmi_down) ? na : dmi_down > dmi_up and dmi_down > 0 ? dmi_down : 0
dmi_trur = ta.rma(ta.tr, dmi_len)
dmi_plus = fixnan(100 * ta.rma(dmi_plusDM, dmi_len) / dmi_trur)
dmi_minus = fixnan(100 * ta.rma(dmi_minusDM, dmi_len) / dmi_trur)
dmi_sum = dmi_plus + dmi_minus
dmi_adx = 100 * ta.rma(math.abs(dmi_plus - dmi_minus) / (dmi_sum == 0 ? 1 : dmi_sum), dmi_lensig)
dmi_gc = dmi_down <= dmi_up
dmi_dc = dmi_down >= dmi_up
dmi_gc_ = ta.crossover(dmi_plus, dmi_adx)
dmi_dc_ = ta.crossunder(dmi_minus, dmi_adx)
plot(show_rd_modul_input ? dmi_adx + rsi_zero_line - dmiadx_zero_line : na, color = dmi_plot_adx_color_input, title = 'DMI ADX', linewidth = 3)
plot(show_rd_modul_input ? dmi_plus + rsi_zero_line - dmiadx_zero_line : na, color = dmi_plot_di_plus_color_input, title = 'DMI DI +', linewidth = 3)
plot(show_rd_modul_input ? dmi_minus + rsi_zero_line - dmiadx_zero_line : na, color = dmi_plot_di_minus_color_input, title = 'DMI DI -', linewidth = 3)
//////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// crossover/crossunder ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_sma = rd_ma(rd_rsi, rd_ma_length_input, rd_ma_type_input)
rd_rsi_sma_gc = ta.crossover(rd_rsi, rd_sma)
rd_rsi_sma_dc = ta.crossunder(rd_rsi, rd_sma)
rd_stoc_rsi_sma_dc = ta.crossover(rd_strsi_k, rd_strsi_d)
rd_stoc_rsi_sma_gc = ta.crossunder(rd_strsi_k, rd_strsi_d)
rd_adx_mfi_gc_ = ta.crossover(rd_mfi_mf, dmi_adx)
rd_adx_mfi_dc_ = ta.crossunder(rd_mfi_mf, dmi_adx)
rd_dmi_plus_adx_gc = ta.crossover(dmi_plus, dmi_adx)
rd_dmi_plus_adx_dc = ta.crossunder(dmi_plus, dmi_adx)
rd_dmi_minus_adx_gc = ta.crossover(dmi_minus, dmi_adx)
rd_dmi_minus_adx_dc = ta.crossunder(dmi_minus, dmi_adx)
rd_cci_gc = ta.crossover(cci, cci_smoothingLine)
rd_cci_dc = ta.crossunder(cci, cci_smoothingLine)
rd_obv_gc = ta.crossover(obv, obv_smoothing_line)
rd_obv_dc = ta.crossunder(obv, obv_smoothing_line)
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// ПАРАМЕТРЫ ВХОД/ВЫХОД ////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
OpenLong_1 = bool(na)
OpenShort_1 = bool(na)
OpenLong_2 = bool(na)
OpenShort_2 = bool(na)
OpenLong_3 = bool(na)
OpenShort_3 = bool(na)
OpenLong_4 = bool(na)
OpenShort_4 = bool(na)
OpenLong_5 = bool(na)
OpenShort_5 = bool(na)
OpenLong_6 = bool(na)
OpenShort_6 = bool(na)
OpenLong_1 := rd_consider_algo_1_input ? rd_cci_gc and 25 < rd_rsi and rd_rsi < rd_factor_rsi_open_long_algo_1_input or rd_cci_gc and rd_rsi > 75 and ta.crossover(close, highUsePivot) and not(open - low > close - open) and osc > volumeThresh : bool(na)
OpenShort_1 := rd_consider_algo_1_input ? rd_cci_dc and 75 > rd_rsi and rd_rsi > rd_factor_rsi_open_short_algo_1_input or rd_cci_dc and rd_rsi < 25 and ta.crossunder(close, lowUsePivot) and not(open - close < high - open) and osc > volumeThresh : bool(na)
OpenLong_2 := rd_consider_algo_2_input ? rd_bull_cond_alert or rd_rsi_sma_gc and rd_rsi_ma < rd_factor_rsi_open_long_algo_2_input : bool(na)
OpenShort_2 := rd_consider_algo_2_input ? rd_bearcondalert or rd_rsi_sma_dc and rd_rsi_ma > rd_factor_rsi_open_short_algo_2_input : bool(na)
OpenLong_3 := rd_consider_algo_3_input ? rd_stoc_rsi_sma_gc and rd_strsi_k < rd_factor_strsi_open_long_algo_3_input : false
OpenShort_3 := rd_consider_algo_3_input ? rd_stoc_rsi_sma_dc and rd_strsi_k > rd_factor_strsi_open_short_algo_3_input : false
OpenLong_4 := rd_consider_algo_4_input ? rd_dmi_plus_adx_gc and 30 < rd_rsi and rd_rsi < rd_factor_rsi_open_long_algo_4_input or rd_dmi_minus_adx_dc and 30 < rd_rsi and rd_rsi < rd_factor_rsi_open_long_algo_4_input or rd_dmi_plus_adx_gc and rd_rsi > 70 : false
OpenShort_4 := rd_consider_algo_4_input ? rd_dmi_minus_adx_gc and 70 > rd_rsi and rd_rsi > rd_factor_rsi_open_short_algo_4_input or rd_dmi_plus_adx_dc and 70 > rd_rsi and rd_rsi > rd_factor_rsi_open_short_algo_4_input or rd_dmi_minus_adx_gc and rd_rsi < 30 : false
OpenLong_5 := rd_consider_algo_5_input ? macd_histo > 0 and macd_histo < 0 and 30 < rd_rsi and rd_rsi < rd_factor_strsi_open_long_algo_5_input or macd_histo > 0 and macd_histo < 0 and rd_rsi > 70 : false
OpenShort_5 := rd_consider_algo_5_input ? macd_histo < 0 and macd_histo > 0 and 70 > rd_rsi and rd_rsi > rd_factor_strsi_open_short_algo_5_input or macd_histo < 0 and macd_histo > 0 and rd_rsi < 30 : false
OpenLong_5 := rd_consider_algo_5_input ? macd_histo > 0 and macd_histo < 0 and 30 < rd_rsi and rd_rsi < rd_factor_strsi_open_long_algo_5_input or macd_histo > 0 and macd_histo < 0 and rd_rsi > 70 : false
OpenShort_5 := rd_consider_algo_5_input ? macd_histo < 0 and macd_histo > 0 and 70 > rd_rsi and rd_rsi > rd_factor_strsi_open_short_algo_5_input or macd_histo < 0 and macd_histo > 0 and rd_rsi < 30 : false
OpenLong_6 := rd_consider_algo_6_input ? rd_obv_gc and 20 < rd_rsi and rd_rsi < rd_factor_rsi_open_long_algo_6_input or rd_obv_gc and rd_rsi > 80 : bool(na)
OpenShort_6 := rd_consider_algo_6_input ? rd_obv_dc and 80 > rd_rsi and rd_rsi > rd_factor_rsi_open_short_algo_6_input or rd_obv_dc and rd_rsi < 20 : bool(na)
////////////////////////////////////////////////////////////////////////////////////////////////////
rd_OpenLong = OpenLong_1 or OpenLong_2 or OpenLong_3 or OpenLong_4 or OpenLong_5 or OpenLong_6
rd_OpenShort = OpenShort_1 or OpenShort_2 or OpenShort_3 or OpenShort_4 or OpenShort_5 or OpenShort_6
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// LABELS LONG/SHORT //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
plotshape(show_long_short_modul_input ? rd_OpenLong : bool(na), force_overlay = true, color = rd_OpenLong_label_color_input, title = 'Open Long Label', text = rd_OpenLong_label_txt, textcolor = rd_Openlabel_textcolor_input, location = location.belowbar, style = shape.labelup, display = display.pane)
plotshape(show_long_short_modul_input ? rd_OpenShort : bool(na), force_overlay = true, color = rd_OpenShort_label_color_input, title = 'Open Short Label', text = rd_OpenShort_label_txt, textcolor = rd_Openlabel_textcolor_input, location = location.abovebar, style = shape.labeldown, display = display.pane)
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// ALERTS LONG/SHORT ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
alertcondition(rd_OpenLong, title = '$ Open long', message = 'Open long {{exchange}}:{{ticker}}, price = {{close}}, volume = {{volume}}')
alertcondition(rd_OpenShort, title = '$ Open short', message = 'Open short {{exchange}}:{{ticker}}, price = {{close}}, volume = {{volume}}')
////////////////////////////////////////////////////////////////////////////////////////////////////
Buy on VolumeThis script has several weaknesses:
1. **Overly Simplistic Logic** – The buy signal is based on just two conditions (DEMA crossing above a Lorentzian Line and a volume spike), which may not be robust enough for real trading conditions.
2. **Lack of Sell Signals** – The script only focuses on buy signals without any exit strategy, making it incomplete for practical trading.
3. **Volume Confirmation May Be Unreliable** – The threshold for volume confirmation (50% above average) is arbitrary and may produce frequent false positives or fail in low-liquidity conditions.
4. **No Risk Management** – There is no stop-loss, take-profit, or risk-adjustment mechanism, making it unsuitable for serious trading.
5. **Potential for Late Entries** – The reliance on moving averages (DEMA) can introduce lag, causing buy signals to appear late after a price move has already occurred.
6. **Limited Adaptability** – The fixed parameter settings (e.g., DEMA period of 6, Lorentzian length of 21) may not work across different market conditions or assets.
7. **No Consideration for Market Trends** – The script does not account for broader market trends, which could lead to poor entries in bearish conditions.
8. **Visual Clutter** – The plotted signals and indicators might create unnecessary chart noise, making it difficult to analyze price action effectively.
9. **Alert Spam Potential** – Without additional filtering conditions, the script may trigger frequent buy alerts, leading to signal fatigue.
Stema sau Banul📜 Povestea Indicatorului „Stema sau Banul” 🎲💰
În vremuri de demult, când piețele financiare erau dominate de strategii complexe și analiști îmbrăcați în costume scumpe, un investitor legendar pe nume Maestrul Stemei și-a pus o întrebare simplă:
👉 „Dacă oricum piețele sunt imprevizibile, de ce să nu lăsăm soarta să decidă?”
Astfel, într-o noapte ploioasă, în fața unui birou plin de grafice și lumânări roșii și verzi, Maestrul Stemei a luat o monedă veche de aur și a început să o arunce.
Dacă ieșea Stema, el cumpăra.
Dacă ieșea Banul, vindea fără ezitare.
Spre uimirea tuturor, strategia sa pur aleatorie a început să rivalizeze cu cele mai sofisticate modele matematice. Traderii de pe Wall Street îl priveau cu neîncredere, iar roboții de tranzacționare încercau să-l copieze. Dar nimeni nu putea egala simplitatea filozofiei sale: „Lasă banul să vorbească”.
Astăzi, moștenirea Maestrului Stemei continuă prin acest indicator, care îți oferă semnale bazate pe vechea metodă a aruncării monedei. Va fi norocul de partea ta? Sau vei blestema ziua în care ai ascultat de un cod care decide aleatoriu? 🎲
💡 Regulă de aur:
➡ Dacă pierzi, spune că e doar o glumă.
➡ Dacă câștigi, pretinde că ai descoperit un algoritm revoluționar.
Acum, Stema sau Banul îți stă la dispoziție! 🎩📈
SOL Multi-Indicator StrategyThis strategy is designed to identify potential trading opportunities in the Solana (SOL) market by combining trend, momentum, and overbought/oversold indicators. Here’s how it works:
1. **Trend Detection with EMAs:**
- The strategy calculates two exponential moving averages (EMAs): a **fast EMA** (shorter period) and a **slow EMA** (longer period).
- **Buy Signal:** When the fast EMA crosses above the slow EMA, it suggests that the short-term price momentum is turning bullish.
- **Sell Signal:** Conversely, when the fast EMA crosses below the slow EMA, it indicates a potential downturn.
2. **Momentum and Overbought/Oversold Check with RSI:**
- The Relative Strength Index (RSI) is used to measure whether the market is overbought or oversold.
- **Buy Signal:** An RSI value below the oversold threshold (e.g., 30) suggests that the market may be undervalued and could be due for a bounce.
- **Sell Signal:** An RSI value above the overbought threshold (e.g., 70) indicates that the market might be overextended and due for a reversal.
3. **Additional Momentum Confirmation with MACD:**
- The MACD (Moving Average Convergence Divergence) indicator is used to gauge momentum changes.
- **Buy Signal:** A bullish crossover, where the MACD line crosses above its signal line, adds further confirmation that upward momentum is building.
- **Sell Signal:** A bearish crossover, where the MACD line crosses below its signal line, reinforces the possibility of declining momentum.
4. **Entry and Exit Conditions:**
- **Entry (Buy):** The strategy initiates a long position when all the following conditions are met:
- The fast EMA crosses above the slow EMA.
- The RSI is below the oversold threshold.
- The MACD line crosses above its signal line.
- **Exit (Sell):** The strategy exits the long position when any one of these conditions occurs:
- The fast EMA crosses below the slow EMA.
- The RSI rises above the overbought threshold.
- The MACD line crosses below its signal line.
5. **Plotting for Visual Confirmation:**
- The EMAs, RSI, and MACD lines are plotted on the chart. The use of `color.new()` ensures that the plotted lines have the desired transparency, making the visual representation clearer.
**Note:**
- This is an example strategy and should be thoroughly backtested and optimized before being used with real money.
- The script does not include additional risk management measures (like stop losses or position sizing beyond a percentage of equity), so you might want to incorporate those based on your trading requirements.
This multi-indicator approach aims to filter out false signals by requiring confirmation from multiple technical tools, ideally helping you capture strong moves in the SOL market.
Fair Value Gap (FVG) Detector//@version=6
indicator("Fair Value Gap (FVG) Detector", overlay=true)
// User Settings
show_bullish_fvg = input(true, title="Show Bullish FVG")
show_bearish_fvg = input(true, title="Show Bearish FVG")
gap_threshold = input(0.5, title="Gap Threshold (%)") / 100 // Minimum gap percentage
// Calculating Fair Value Gaps
prev_high = high
prev_low = low
current_low = low
current_high = high
// Bullish Fair Value Gap (Previous high > Current low)
bullish_fvg = show_bullish_fvg and (prev_high > current_low) and ((prev_high - current_low) / prev_high > gap_threshold)
// Bearish Fair Value Gap (Previous low < Current high)
bearish_fvg = show_bearish_fvg and (prev_low < current_high) and ((current_high - prev_low) / prev_low > gap_threshold)
// Plot Bullish FVG
if bullish_fvg
var box b = na
b := box.new(left=bar_index , right=bar_index, top=prev_high, bottom=current_low, bgcolor=color.new(color.green, 90), border_color=color.green)
// Plot Bearish FVG
if bearish_fvg
var box b = na
b := box.new(left=bar_index , right=bar_index, top=current_high, bottom=prev_low, bgcolor=color.new(color.red, 90), border_color=color.red)
Sector Momentum SupertrendWhat This Indicator Does:
✔ Tracks sector strength (e.g., NIFTY IT, BANK NIFTY, etc.)
✔ Compares stock vs sector trend using moving averages (SMA 10 & 20)
✔ Generates Buy/Sell signals when a stock outperforms or underperforms its sector
✔ Plots a Supertrend-like signal line with green for buy & red for sell
Effective FVG Indicator - ImranDescription:
The Effective FVG Indicator is a technical analysis tool designed to identify Fair Value Gaps (FVGs) in financial markets. FVGs occur when there is a significant gap between the closing price of one session and the opening price of the next session, often indicating a potential reversal point. This indicator uses volume and price movement criteria to confirm and mark these gaps effectively.
Key Features:
Fair Value Gap Detection : Identifies both bullish and bearish FVGs based on significant gaps in price.
Volume Confirmation : Confirms FVGs with high volume, ensuring that the gap is not due to a lack of liquidity.
Price Imbalance : Ensures that the gap is accompanied by a large price movement within the session, indicating strong market sentiment.
Buy/Sell Signals : Marks bullish FVGs with a green "BUY" label below the bar and bearish FVGs with a red "SELL" label above the bar.
Background Highlighting : Highlights the background with a semi-transparent green or red color when a valid FVG is detected, making it easy to spot significant gaps.
Bank Nifty Strategy with Entry, SL, and TPstartegy that can give you buy and sell signals, fiest test
MA Cloud Indicator/ User Inputs for MA Type Selection
ma_type = input.string("EMA", title="Moving Average Type", options= )
// User Inputs for MA Periods and Timeframes
ma9_length = input(9, title="9 MA Length")
ma21_length = input(21, title="21 MA Length")
ma200_length = input(200, title="200 MA Length")
EMA Cloud Strategy by SumitGreen cloud when price above 9 ema and 9 ema above 21 ema, Red cloud when price below 9 ema and 9 ema below 21 ema
Candlestick Pattern Detector - Vijay PrasadOverview:
This Pine Script v6 indicator is designed to detect and label key candlestick patterns on TradingView charts. It provides real-time visual markers for major bullish and bearish reversal signals, aiding traders in decision-making.
Usefulness:
✅ Saves time by automating candlestick pattern detection.
✅ Reduces manual chart analysis errors.
✅ Works across all markets & timeframes.
✅ Enhances trading strategies with accurate signals.
Candlestick Patterns Recognises:
Bullish Engulfing – A strong bullish reversal pattern.
Bearish Engulfing – Indicates a potential downtrend.
Hammer – Suggests a market bottom or reversal.
Shooting Star – A bearish reversal signal at the top of an uptrend.
Doji – Signals market indecision and possible trend change.
Key Functions:
Automated Pattern Visible
Identifies candlestick patterns dynamically and plots them on the chart.
Visual Labels for Patterns
Labels to indicate specific candlestick formations.
Labels appear only when a valid pattern is detected, avoiding unnecessary clutter.
Buy/Sell Signal
Plots buy signals at bullish patterns and sell signals at bearish patterns.
Helps traders recognize trend reversals and entry/exit points.
Bullish Engulfing Pattern (Green Label)
What it means: A bullish engulfing pattern typically signals a potential reversal from a downtrend to an uptrend. The current candle fully engulfs the previous candle, signaling strong buying interest.
Identifying Candlestick Patterns on the Chart
How to use it:
Entry: Look for a green label (bullish engulfing) at the bottom of the chart. When it appears, consider entering a long position (buy).
Confirmation: To increase reliability, wait for confirmation by observing if price moves above the high of the bullish engulfing candle.
Exit: Exit when the trend shows signs of reversing or take profit at predefined levels (e.g., resistance or a risk-to-reward ratio).
Bearish Engulfing Pattern (Red Label)
What it means: A bearish engulfing pattern is a signal of a potential reversal from an uptrend to a downtrend. The current candle fully engulfs the previous candle, signaling strong selling pressure.
How to use it:
Entry: Look for a red label (bearish engulfing) at the top of the chart. When it appears, consider entering a short position (sell).
Confirmation: Wait for the price to move below the low of the bearish engulfing candle to confirm the bearish trend.
Exit: Close the trade when the price reaches support levels or the trend shows signs of reversing.
Doji Pattern (Blue Circle)
What it means: A Doji candle signals market indecision. It represents a balance between buyers and sellers, often marking a potential reversal or consolidation point.
How to use it:
Entry: If the Doji appears after a strong trend (bullish or bearish), wait for the next candle to break above or below the Doji's high or low. This can signal a continuation or reversal.
Confirmation: You can look for additional indicators like moving averages, RSI, or MACD for confirmation before taking any action.
Exit: Exit when the price shows clear momentum in your entry direction.
Hammer Pattern (Orange Triangle)
What it means: The hammer pattern is a bullish reversal pattern that appears after a downtrend. It suggests that sellers pushed the price down during the session, but buyers managed to push the price back up.
How to use it:
Entry: When a hammer appears, consider entering a long position (buy). The price should move above the hammer's high for confirmation.
Confirmation: Look for strong volume and a follow-up bullish candle to confirm the reversal.
Exit: Set a target based on the next resistance level, or use a trailing stop to lock in profits.
Using Candlestick Patterns with Other Indicators
To increase your chances of success, combine candlestick patterns with other technical indicators.
Here are some ideas:
RSI (Relative Strength Index): Use RSI to check whether the market is overbought or oversold. A bullish engulfing in an oversold market could indicate a stronger buy signal, and a bearish engulfing in an overbought market could indicate a stronger sell signal.
Moving Averages (e.g., 50 EMA, 200 EMA): Confirm trend direction. If the candlestick pattern aligns with the direction of the moving averages, it can give a stronger signal.
MACD (Moving Average Convergence Divergence): Use MACD to confirm momentum and potential trend changes. If a candlestick pattern aligns with a MACD crossover, it strengthens the signal.
Volume: Look for higher-than-average volume when a pattern appears. This can give you additional confirmation that the market is reacting strongly.
Practice and Refine
It's important to practice using the candlestick patterns in a demo account or backtest them to see how they perform under different market conditions. Over time, you can adjust the settings and patterns to fit your trading style and preferences.
Trend Strength Gauge sam//@version=6
indicator("Trend Strength Gauge", overlay=true)
// Input for indicators
lengthMA = input.int(50, title="Moving Average Length")
lengthATR = input.int(14, title="ATR Length")
lengthRSI = input.int(14, title="RSI Length")
rsiOverbought = input.int(70, title="RSI Overbought Level")
rsiOversold = input.int(30, title="RSI Oversold Level")
// Calculating Moving Averages
maShort = ta.sma(close, lengthMA)
maLong = ta.sma(close, lengthMA * 2) // Using a longer period for trend confirmation
// Calculating ATR for volatility
atrValue = ta.atr(lengthATR)
// Calculating RSI for momentum
rsiValue = ta.rsi(close, lengthRSI)
// Trend Strength Calculation
trendDirection = maShort > maLong ? 1 : -1
volatilityFactor = atrValue / close
momentumFactor = rsiValue > rsiOverbought ? -1 : (rsiValue < rsiOversold ? 1 : 0)
// Trend Strength Formula (0 to 100)
strength = (trendDirection * 50 + volatilityFactor * 50 + momentumFactor * 50)
// Normalize strength to be between 0 and 100
strength := math.min(math.max(strength, 0), 100)
// Plot the Trend Strength Gauge as a histogram
plot(strength, title="Trend Strength", color=color.new(color.blue, 0), linewidth=2, style=plot.style_histogram)
// Color the background based on trend strength
bgcolor(strength > 70 ? color.new(color.green, 90) : (strength < 30 ? color.new(color.red, 90) : na))
// Plot the moving averages on the chart for reference
plot(maShort, title="Short MA", color=color.green, linewidth=2)
plot(maLong, title="Long MA", color=color.red, linewidth=2)
Power Law Below is a detailed, line-by-line explanation in English of the Pine Script (TradingView) code. It uses Pine Script v6 syntax.
---
```pine
//@version=6
indicator("Power Law", overlay=true)
```
1. `//@version=6`
- Declares that this script uses Pine Script version 6. It must appear on the very first line.
2. `indicator("Power Law", overlay=true)`
- Defines this script as an indicator named **"Power Law"**.
- `overlay=true` means this indicator is plotted on the main chart (the price chart) rather than in a separate pane.
---
```pine
// Days X-Axis Value
start = time == timestamp(2010, 7, 18, 0, 0)
days = request.security("INDEX:BTCUSD", 'D', ta.barssince(start))
offset = 561 // days between 2009/1/1 and "start"
d = days + offset
```
1. `start = time == timestamp(2010, 7, 18, 0, 0)`
- Checks if the current bar’s `time` equals July 18, 2010 at 00:00. This returns a boolean value (`true` or `false`).
- It’s mainly used together with `ta.barssince(start)` to calculate the number of bars elapsed since this “start” date.
2. `days = request.security("INDEX:BTCUSD", 'D', ta.barssince(start))`
- `request.security()` lets the script request data from another symbol or another timeframe—in this case, `"INDEX:BTCUSD"` on the Daily (`'D'`) timeframe.
- The third argument, `ta.barssince(start)`, is a built-in function in Pine that counts how many bars have passed since `start` was `true`. In this script, it effectively measures how many daily bars have elapsed since July 18, 2010.
- The result is assigned to `days`, indicating “the count of daily bars between July 18, 2010 and the most recent daily bar in the BTC index.”
3. `offset = 561`
- A user-defined number. The comment states it’s the number of days between January 1, 2009, and the “start” date (July 18, 2010). It is used to calibrate or shift the day count.
4. `d = days + offset`
- Adds the offset to `days`, giving a final day-count-like value (`d`) that the script uses later in the power-law calculations.
---
```pine
a = input(-17.668, "Power Law Intercept", group="Power Law Settings")
b = input(5.926, "Power Law Slope", group="Power Law Settings")
```
- These lines define two adjustable parameters `a` and `b` using `input()`, making them editable via the indicator’s settings.
- `a` (the intercept) is labeled “Power Law Intercept.”
- `b` (the slope) is labeled “Power Law Slope.”
- `group="Power Law Settings"` puts them into a named group in the settings dialog.
---
```pine
price_power_law_0 = math.pow(10, a + b*math.log10(d))
price_power_law_1 = math.pow(10, a + b*math.log10(d + 1*365))
price_power_law_2 = math.pow(10, a + b*math.log10(d + 2*365))
price_power_law_3 = math.pow(10, a + b*math.log10(d + 3*365))
price_power_law_4 = math.pow(10, a + b*math.log10(d + 4*365))
price_power_law_5 = math.pow(10, a + b*math.log10(d + 5*365))
```
- These lines each calculate a “power law” price value:
\
- `d` is the base day count.
- `math.log10(...)` takes the base-10 logarithm.
- `a` is the intercept; `b` is the slope in the power-law model.
- Adding `(1*365), (2*365), ...` to `d` suggests forecasts or curves 1 year, 2 years, etc. beyond the baseline.
- `math.pow(10, ... )` is simply 10 raised to the power of `(a + b * log10(...))`.
---
```pine
// Use a valid 6-digit color code (e.g. #FFFFAA) or 8-digit (e.g. #FFFFAA80)
p0 = plot(price_power_law_0, color=#FFFFAA, title="Power Law", linewidth=1)
p1 = plot(price_power_law_1, title="Power Law 1", linewidth=1, color=bar_index % 2 == 0 ? #FFFFAA : #000000)
p2 = plot(price_power_law_2, title="Power Law 2", linewidth=1, color=bar_index % 2 == 0 ? #FFFFAA : #000000)
p3 = plot(price_power_law_3, title="Power Law 3", linewidth=1, color=bar_index % 2 == 0 ? #FFFFAA : #000000)
p4 = plot(price_power_law_4, title="Power Law 4", linewidth=1, color=bar_index % 2 == 0 ? #FFFFAA : #000000)
p5 = plot(price_power_law_5, title="Power Law 5", linewidth=1, color=bar_index % 2 == 0 ? #FFFFAA : #000000)
```
1. The script plots six lines (from `price_power_law_0` to `price_power_law_5`).
2. `color=#FFFFAA`
- A 6-digit hex color (`#RRGGBB`) that sets the line’s color.
3. `color=bar_index % 2 == 0 ? #FFFFAA : #000000`
- A conditional color assignment: if `bar_index % 2 == 0`, the color is `#FFFFAA`, otherwise it is `#000000`. This makes line colors alternate depending on the bar index.
4. `linewidth=1` sets the thickness of each line.
5. `title="Power Law X"` sets each line’s label in the chart’s legend.
---
## How It Works
- The script calculates how many daily bars have passed since July 18, 2010 (plus a manual offset of 561 days).
- It then applies a power-law formula for various offsets (`+ 1*365`, etc.), each representing a different curve.
- Finally, it plots these six curves on the main chart, showing potential price trajectories or “power-law” relationships for Bitcoin’s historical data (taken from `"INDEX:BTCUSD"` on a daily timeframe).
## Important Notes
1. **Color Codes**
- Must be valid 6-digit or 8-digit hex codes (e.g. `#FFFFAA` or `#FFFFAA80`). Otherwise, you’ll get a syntax error.
2. **`request.security()`**
- Fetching data from `"INDEX:BTCUSD"` on a daily timeframe. If your chart is on another symbol or timeframe, the script still references the daily bars from that index, which can lead to alignment differences.
3. **Logarithms**
- Make sure `d` (or `d + n*365`) never becomes zero or negative, otherwise `math.log10()` will fail. If your script tries to log10(0) or a negative number, you’ll get an error.
4. **Conceptual Use**
- This script’s logic is specific to modeling Bitcoin’s price over time using a power-law approach. You can change the `start` date, the offset, or the intercept/slope inputs to adapt the script for different data sources or fitting strategies.
---
**In summary,** this script draws several power-law curves on the chart based on a reference date (July 18, 2010) and an offset, presumably chosen to align with Bitcoin’s historical timeline. By adjusting `a` (the intercept) and `b` (the slope), you can fine-tune how these curves fit the historical data.
BankNifty/Nifty Breakout StrategyHere is your TradingView Pine Script for the Nifty/Bank Nifty options breakout strategy. It includes CPR levels, VWAP, Supertrend, and RSI for signals. It also sets alerts for call and put buying conditions.