รูปแบบชาร์ต
3Time ZonesUso de 3 Zonas de tiempos a la vez para customizar. Predeterminadamente trae la división diaria, zona de operativa de New York y como 3ra los horarios de manipulaciones del mercado en NY 👍✌️
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)
Pegofe Universal Breakout StrategyDescription for TradingView Publication
Title: Pegofe NY Breakout Strategy – EUR/USD (1:2 Risk/Reward)
Description:
The Pegofe NY Breakout Strategy is designed to capture high-probability trading opportunities in EUR/USD at the opening of the New York session (15:30 Spain / 14:30 UTC) on a 5-minute timeframe.
Key Features:
✅ Trend Confirmation: Uses EMA 50 and EMA 9 to filter high-probability trades.
✅ Momentum-Based Entries: Combines RSI (14) and EMA crossovers to detect overbought/oversold conditions.
✅ Risk-Reward Ratio of 1:2: Automatically calculates Stop Loss (SL) and Take Profit (TP) based on ATR (14) for dynamic volatility adjustment.
✅ Clear Trade Signals: Visual buy and sell signals appear when the entry criteria are met.
✅ Stop Loss & Take Profit Labels: Displays SL and TP levels on the chart using label.new() for better visualization.
Entry Conditions:
📈 Long Entry (Buy Signal):
• The price is above EMA 50 (uptrend).
• RSI < 35 (oversold).
• EMA 9 crosses above the price.
• The trade occurs after 14:30 UTC (New York session open).
📉 Short Entry (Sell Signal):
• The price is below EMA 50 (downtrend).
• RSI > 65 (overbought).
• EMA 9 crosses below the price.
• The trade occurs after 14:30 UTC (New York session open).
How It Works:
• When a valid trade setup occurs, the strategy executes an entry order and automatically sets a Stop Loss (1.5x ATR) and Take Profit (2x SL).
• The SL and TP levels are dynamically adjusted based on market volatility.
• The script labels SL and TP directly on the chart for better tracking.
Recommended Settings:
• Market: EUR/USD
• Timeframe: 5 minutes
• Session: After 14:30 UTC (New York open)
🚀 Try it now and optimize your NY session trading!
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
Smart Pattern Predictor// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © payattentionjay
//@version=6
strategy("Smart Whale Pattern Predictor", overlay=true)
// === PARAMETERS ===
lengthEMA = input(50, title="EMA Length")
lengthVWAP = input(20, title="VWAP Length")
rsiLength = input(14, title="RSI Length")
macdShort = input(12, title="MACD Short EMA")
macdLong = input(26, title="MACD Long EMA")
macdSignal = input(9, title="MACD Signal Length")
whaleVolumeMultiplier = input(2.5, title="Whale Volume Multiplier")
// === INDICATORS ===
// Trend Confirmation
emaTrend = ta.ema(close, lengthEMA)
vwapTrend = ta.vwap(close)
// Momentum & Overbought/Oversold Levels
rsiValue = ta.rsi(close, rsiLength)
macdLine = ta.ema(close, macdShort) - ta.ema(close, macdLong)
macdSignalLine = ta.ema(macdLine, macdSignal)
macdHistogram = macdLine - macdSignalLine
// Whale Activity Detection (Unusual Volume Spikes)
avgVolume = ta.sma(volume, 20)
whaleTrade = volume > (avgVolume * whaleVolumeMultiplier)
// === CHART PATTERN DETECTION ===
// Head & Shoulders Detection
leftShoulder = ta.highest(high, 20)
head = ta.highest(high, 10)
rightShoulder = ta.highest(high, 20)
headAndShoulders = leftShoulder < head and rightShoulder < head and leftShoulder > rightShoulder
// Double Top & Double Bottom Detection
doubleTop = ta.highest(high, 20) == ta.highest(high, 40) and close < ta.highest(high, 20)
doubleBottom = ta.lowest(low, 20) == ta.lowest(low, 40) and close > ta.lowest(low, 20)
// Triangle Patterns (Ascending & Descending)
ascendingTriangle = ta.highest(high, 20) > ta.highest(high, 40) and ta.lowest(low, 20) > ta.lowest(low, 40)
descendingTriangle = ta.highest(high, 20) < ta.highest(high, 40) and ta.lowest(low, 20) < ta.lowest(low, 40)
// Future Price Prediction Based on Pattern Breakout
futureUpMove = headAndShoulders == false and (doubleBottom or ascendingTriangle)
futureDownMove = headAndShoulders or doubleTop or descendingTriangle
// === ENTRY & EXIT CONDITIONS ===
// Buy Conditions
longCondition = ta.crossover(close, emaTrend) and rsiValue < 50 and macdLine > macdSignalLine and whaleTrade and futureUpMove
if (longCondition)
strategy.entry("Long", strategy.long)
// Sell Conditions
shortCondition = ta.crossunder(close, emaTrend) and rsiValue > 50 and macdLine < macdSignalLine and whaleTrade and futureDownMove
if (shortCondition)
strategy.entry("Short", strategy.short)
// === PLOT CHART PATTERNS ===
plotshape(headAndShoulders, location=location.abovebar, color=color.red, style=shape.triangleup, title="Head & Shoulders Detected")
plotshape(doubleTop, location=location.abovebar, color=color.orange, style=shape.triangleup, title="Double Top Detected")
plotshape(doubleBottom, location=location.belowbar, color=color.green, style=shape.triangledown, title="Double Bottom Detected")
plotshape(ascendingTriangle, location=location.abovebar, color=color.blue, style=shape.triangleup, title="Ascending Triangle Detected")
plotshape(descendingTriangle, location=location.belowbar, color=color.purple, style=shape.triangledown, title="Descending Triangle Detected")
// === PLOT TREND INDICATORS ===
plot(emaTrend, color=color.blue, title="EMA 50")
plot(vwapTrend, color=color.orange, title="VWAP")
// === ALERT SYSTEM ===
alertcondition(longCondition, title="Buy Alert", message="BUY SIGNAL: Strong entry detected with pattern breakout!")
alertcondition(shortCondition, title="Sell Alert", message="SELL SIGNAL: Downtrend detected with pattern breakdown!")
// === END OF SCRIPT ===
Pegofe Universal Breakout StrategyDescription for TradingView Publication
Title: Pegofe NY Breakout Strategy – EUR/USD (1:2 Risk/Reward)
Description:
The Pegofe NY Breakout Strategy is designed to capture high-probability trading opportunities in EUR/USD at the opening of the New York session (15:30 Spain / 14:30 UTC) on a 5-minute timeframe.
Key Features:
✅ Trend Confirmation: Uses EMA 50 and EMA 9 to filter high-probability trades.
✅ Momentum-Based Entries: Combines RSI (14) and EMA crossovers to detect overbought/oversold conditions.
✅ Risk-Reward Ratio of 1:2: Automatically calculates Stop Loss (SL) and Take Profit (TP) based on ATR (14) for dynamic volatility adjustment.
✅ Clear Trade Signals: Visual buy and sell signals appear when the entry criteria are met.
✅ Stop Loss & Take Profit Labels: Displays SL and TP levels on the chart using label.new() for better visualization.
Entry Conditions:
📈 Long Entry (Buy Signal):
• The price is above EMA 50 (uptrend).
• RSI < 35 (oversold).
• EMA 9 crosses above the price.
• The trade occurs after 14:30 UTC (New York session open).
📉 Short Entry (Sell Signal):
• The price is below EMA 50 (downtrend).
• RSI > 65 (overbought).
• EMA 9 crosses below the price.
• The trade occurs after 14:30 UTC (New York session open).
How It Works:
• When a valid trade setup occurs, the strategy executes an entry order and automatically sets a Stop Loss (1.5x ATR) and Take Profit (2x SL).
• The SL and TP levels are dynamically adjusted based on market volatility.
• The script labels SL and TP directly on the chart for better tracking.
Recommended Settings:
• Market: EUR/USD
• Timeframe: 5 minutes
• Session: After 14:30 UTC (New York open)
🚀 Try it now and optimize your NY session trading!
AB=CD Reciprocal Ratios Table (Source Code)Harmonics AB=CD. C Retracement and D Extension Calculations Table
Price-Aligned Trend Indicator//@version=6
indicator("Price-Aligned Trend Indicator", overlay=true)
// Input parameters
t3Length1 = input.int(5, "Fast T3 Length")
t3Length2 = input.int(13, "Medium T3 Length")
t3Length3 = input.int(34, "Slow T3 Length")
// T3 Moving Average Function
t3(src, len) =>
e1 = ta.ema(src, len)
e2 = ta.ema(e1, len)
e3 = ta.ema(e2, len)
e4 = ta.ema(e3, len)
(e1 + 2 * e2 + 2 * e3 + e4) / 6
// Moving averages
maFast = t3(close, t3Length1)
maMedium = t3(close, t3Length2)
maSlow = t3(close, t3Length3)
// Conditions for trends
bullish = maFast > maMedium and maMedium > maSlow
bearish = maFast < maMedium and maMedium < maSlow
// Trend clouds
pFast = plot(maFast, color=bullish ? color.new(color.green, 0) : bearish ? color.new(color.red, 0) : color.new(color.gray, 0), linewidth=2)
pMedium = plot(maMedium, color=bullish ? color.new(color.green, 30) : bearish ? color.new(color.red, 30) : color.new(color.gray, 30), linewidth=2)
pSlow = plot(maSlow, color=bullish ? color.new(color.green, 60) : bearish ? color.new(color.red, 60) : color.new(color.gray, 60), linewidth=2)
fill(pFast, pMedium, color=bullish ? color.new(color.green, 80) : bearish ? color.new(color.red, 80) : color.new(color.gray, 90))
// Breakout/Breakdown Labels
if ta.crossover(maFast, maMedium) and bullish
label.new(x=bar_index, y=close, text="BREAKOUT", style=label.style_label_up, color=color.green, textcolor=color.white)
if ta.crossunder(maFast, maMedium) and bearish
label.new(x=bar_index, y=close, text="BREAKDOWN", style=label.style_label_down, color=color.red, textcolor=color.white)
[SHORT ONLY] Internal Bar Strength (IBS) Mean Reversion Strategy█ STRATEGY DESCRIPTION
The "Internal Bar Strength (IBS) Strategy" is a mean-reversion strategy designed to identify trading opportunities based on the closing price's position within the daily price range. It enters a short position when the IBS indicates overbought conditions and exits when the IBS reaches oversold levels. This strategy is Short-Only and was designed to be used on the Daily timeframe for Stocks and ETFs.
█ WHAT IS INTERNAL BAR STRENGTH (IBS)?
Internal Bar Strength (IBS) measures where the closing price falls within the high-low range of a bar. It is calculated as:
IBS = (Close - Low) / (High - Low)
- Low IBS (≤ 0.2) : Indicates the close is near the bar's low, suggesting oversold conditions.
- High IBS (≥ 0.8) : Indicates the close is near the bar's high, suggesting overbought conditions.
█ SIGNAL GENERATION
1. SHORT ENTRY
A Short Signal is triggered when:
The IBS value rises to or above the Upper Threshold (default: 0.9).
The Closing price is greater than the previous bars High (close>high ).
The signal occurs within the specified time window (between `Start Time` and `End Time`).
2. EXIT CONDITION
An exit Signal is generated when the IBS value drops to or below the Lower Threshold (default: 0.3). This prompts the strategy to exit the position.
█ ADDITIONAL SETTINGS
Upper Threshold: The IBS level at which the strategy enters trades. Default is 0.9.
Lower Threshold: The IBS level at which the strategy exits short positions. Default is 0.3.
Start Time and End Time: The time window during which the strategy is allowed to execute trades.
█ PERFORMANCE OVERVIEW
This strategy is designed for Stocks and ETFs markets and performs best when prices frequently revert to the mean.
The strategy can be optimized further using additional conditions such as using volume or volatility filters.
It is sensitive to extreme IBS values, which help identify potential reversals.
Backtesting results should be analyzed to optimize the Upper/Lower Thresholds for specific instruments and market conditions.
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}}')
////////////////////////////////////////////////////////////////////////////////////////////////////
Fair Value Gap Strategyffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff
Price-Aligned Trend IndicatorPrice-Aligned Trend IndicatoPrice-Aligned Trend IndicatoPrice-Aligned Trend IndicatoPrice-Aligned Trend Indicato
AI-Based Quotex OTC Signal v2 (Updated for Pine Script v6)This advanced Pine Script is designed for 1-minute binary options trading. It generates non-repainting CALL and PUT signals using a combination of RSI, ATR, moving averages, and volume filters. The script avoids choppy markets and adapts to changing conditions, ensuring high-quality signals with minimal false alerts. Perfect for traders looking for a reliable and adaptive strategy.
Stick Sandwich Pattern# Stick Sandwich Pattern Indicator
## Description
The Stick Sandwich Pattern Indicator is a custom TradingView script that identifies specific three-candle patterns in financial markets. The indicator uses a sandwich emoji (🥪) to mark pattern occurrences directly on the chart, making it visually intuitive and easy to spot potential trading opportunities.
## Pattern Types
### Bullish Stick Sandwich
A bullish stick sandwich pattern is identified when:
- First candle: Bullish (close > open)
- Second candle: Bearish (close < open)
- Third candle: Bullish (close > open)
- The closing price of the third candle is within 10% of the first candle's range from its closing price
### Bearish Stick Sandwich
A bearish stick sandwich pattern is identified when:
- First candle: Bearish (close < open)
- Second candle: Bullish (close > open)
- Third candle: Bearish (close < open)
- The closing price of the third candle is within 10% of the first candle's range from its closing price
## Technical Implementation
- Written in Pine Script v5
- Runs as an overlay indicator
- Uses a 10% tolerance range for closing price comparison
- Implements rolling pattern detection over the last 3 candles
- Break statement ensures only the most recent pattern is marked
## Visual Features
- Bullish patterns: Green sandwich emoji above the pattern
- Bearish patterns: Red sandwich emoji below the pattern
- Label size: Small
- Label styles:
- Bullish: Label points upward
- Bearish: Label points downward
## Usage
1. Add the indicator to your TradingView chart
2. Look for sandwich emojis that appear above or below price bars
3. Green emojis indicate potential bullish reversals
4. Red emojis indicate potential bearish reversals
## Code Structure
- Main indicator function with overlay setting
- Two separate functions for pattern detection:
- `bullishStickSandwich()`
- `bearishStickSandwich()`
- Pattern scanning loop that checks the last 3 candles
- Built-in label plotting for visual identification
## Formula Details
The closing price comparison uses the following tolerance calculation:
```
Tolerance = (High - Low of first candle) * 0.1
Valid if: |Close of third candle - Close of first candle| <= Tolerance
```
## Notes
- The indicator marks patterns in real-time as they form
- Only the most recent pattern within the last 3 candles is marked
- Pattern validation includes both candle direction and closing price proximity
- The 10% tolerance helps filter out weak patterns while catching meaningful ones
## Disclaimer
This indicator is for informational purposes only. Always use proper risk management and consider multiple factors when making trading decisions.
Probability Signal This Pine Script code is designed for use on the TradingView platform to help traders make decisions based on certain technical indicators. Here's an explanation of how the code functions overall:
Strategy Setup:
The strategy is titled "Probability Signal " and is overlaid on the chart.
The default position size is set to 10% of equity.
Inputs:
Several user-defined inputs are provided for the strategy, including:
length (Regression Length): The number of periods to consider for calculating the Linear Regression line.
smoothing: A smoothing period for the Linear Regression line.
deviation: A multiplier used to define the width of the bands (calculated using standard deviation).
useMACD: A boolean option to activate a MACD filter for buy/sell signals.
useStrategy: A boolean option to enable the strategy tester for backtesting purposes.
TP_pips_input and SL_pips_input: Define the take profit and stop loss values in pips (user-defined settings).
MACD Calculation:
The Moving Average Convergence Divergence (MACD) is calculated using the source data (close price). This helps filter out trade signals based on the MACD's position relative to zero.
Linear Regression Line (LRL) and Smoothing:
A Linear Regression line is calculated using the ta.linreg() function.
The result is then smoothed using a simple moving average (ta.sma()), allowing for a more stable representation of price trends.
Standard Deviation and Bands:
The standard deviation of the source data (close price) is calculated.
The upper and lower bands are created around the smoothed regression line by adding and subtracting a multiple of the standard deviation (based on the deviation input).
Trend Slope and Trend Detection:
The slope of the smoothed regression line is calculated to determine whether the trend is upwards (green) or downwards (red).
If the trend changes (bullish or bearish cross), a signal is generated.
Buy/Sell Signal Validation:
A bullish signal (valid buy) is generated when the trend shifts from red to green, and optionally when the MACD line is below zero (if the MACD filter is activated).
A bearish signal (valid sell) occurs when the trend shifts from green to red, and optionally when the MACD line is above zero.
Labeling and Alerts:
When a buy or sell signal is validated, a corresponding label ("BUY" or "SELL") is displayed on the chart, slightly offset from the low/high of the candle.
A dynamic alert message is generated, showing the entry price, take profit (TP) level, and stop loss (SL) level for the trade.
Strategy Orders (When Strategy Tester is Enabled):
If the strategy tester is enabled (useStrategy = true), buy and sell entries are placed:
For a buy, a "Long" position is entered, and a corresponding exit order is placed based on the user-defined TP and SL levels.
For a sell, a "Short" position is entered, and similarly, the exit order is based on the TP and SL.
The script, overall, aims to give trade signals (buy and sell) based on a combination of trend analysis using Linear Regression and optionally filtered by MACD. It also allows for backtesting with the strategy tester, using stop loss and take profit targets set in pips.
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