OPEN-SOURCE SCRIPT

Hidden Divergence with S/R & TP

19
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/
// © Gemini

// version=5
// This indicator combines Hidden RSI Divergence with Support & Resistance detection
// and provides dynamic take-profit targets based on ATR. It also includes alerts.
indicator("Hidden Divergence with S/R & TP", overlay=true)

// === INPUTS ===
rsiLengthInput = input.int(14, "RSI Length", minval=1)
rsiSMALengthInput = input.int(5, "RSI SMA Length", minval=1)
pivotLookbackLeft = input.int(5, "Pivot Left Bars", minval=1)
pivotLookbackRight = input.int(5, "Pivot Right Bars", minval=1)
atrPeriodInput = input.int(14, "ATR Period", minval=1)
atrMultiplierTP1 = input.float(1.5, "TP1 ATR Multiplier", minval=0.1)
atrMultiplierTP2 = input.float(3.0, "TP2 ATR Multiplier", minval=0.1)
atrMultiplierTP3 = input.float(5.0, "TP3 ATR Multiplier", minval=0.1)

// === CALCULATIONS ===
// Calculate RSI and its SMA
rsiValue = ta.rsi(close, rsiLengthInput)
rsiSMA = ta.sma(rsiValue, rsiSMALengthInput)

// Calculate Average True Range for Take Profits
atrValue = ta.atr(atrPeriodInput)

// Identify pivot points for Support and Resistance
pivotLow = ta.pivotlow(pivotLookbackLeft, pivotLookbackRight)
pivotHigh = ta.pivothigh(pivotLookbackLeft, pivotLookbackRight)

// Define variables to track divergence and TP levels
var bool bullishDivergence = false
var bool bearishDivergence = false
var float tp1Buy = na
var float tp2Buy = na
var float tp3Buy = na
var float tp1Sell = na
var float tp2Sell = na
var float tp3Sell = na

// Reset divergence flags at each new bar
bullishDivergence := false
bearishDivergence := false

// === HIDDEN DIVERGENCE LOGIC ===
// Hidden Bullish Divergence (Higher low in price, lower low in RSI)
// Price makes a higher low, while RSI makes a lower low, suggesting trend continuation.
for i = 1 to 50 // Look back up to 50 bars for a confirmed pivot low
if not na(pivotLow) and close < close and rsiValue < rsiValue
// Check if price is making a higher low than the pivot low, and RSI is making a lower low
if low > low and rsiValue < rsiValue
bullishDivergence := true
break // Exit loop once divergence is found

// Hidden Bearish Divergence (Lower high in price, higher high in RSI)
// Price makes a lower high, while RSI makes a higher high, suggesting trend continuation.
for i = 1 to 50 // Look back up to 50 bars for a confirmed pivot high
if not na(pivotHigh) and close > close and rsiValue > rsiValue
// Check if price is making a lower high than the pivot high, and RSI is making a higher high
if high < high and rsiValue > rsiValue
bearishDivergence := true
break // Exit loop once divergence is found

// === SETTING TP LEVELS AND ALERTS ===
if bullishDivergence
buySignalPrice = low - atrValue * 0.5 // Entry below the low
tp1Buy := buySignalPrice + atrValue * atrMultiplierTP1
tp2Buy := buySignalPrice + atrValue * atrMultiplierTP2
tp3Buy := buySignalPrice + atrValue * atrMultiplierTP3

// Alert for buying signal
alert("Hidden Bullish Divergence Detected on " + syminfo.ticker + " - Buy Signal", alert.freq_once_per_bar_close)
else
tp1Buy := na
tp2Buy := na
tp3Buy := na

if bearishDivergence
sellSignalPrice = high + atrValue * 0.5 // Entry above the high
tp1Sell := sellSignalPrice - atrValue * atrMultiplierTP1
tp2Sell := sellSignalPrice - atrValue * atrMultiplierTP2
tp3Sell := sellSignalPrice - atrValue * atrMultiplierTP3

// Alert for selling signal
alert("Hidden Bearish Divergence Detected on " + syminfo.ticker + " - Sell Signal", alert.freq_once_per_bar_close)
else
tp1Sell := na
tp2Sell := na
tp3Sell := na


// === PLOTTING SIGNALS AND TAKE PROFITS ===
// Plotting shapes for buy/sell signals
plotshape(bullishDivergence, title="Buy Signal", style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), text="Buy", textcolor=color.black)
plotshape(bearishDivergence, title="Sell Signal", style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), text="Sell", textcolor=color.black)

// Plotting take-profit lines
plot(tp1Buy, "TP1 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp2Buy, "TP2 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp3Buy, "TP3 Buy", color=color.new(color.lime, 0), style=plot.style_linebr)
plot(tp1Sell, "TP1 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)
plot(tp2Sell, "TP2 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)
plot(tp3Sell, "TP3 Sell", color=color.new(color.orange, 0), style=plot.style_linebr)

// Plotting the RSI and its SMA on a sub-pane
plot(rsiValue, "RSI", color.new(color.fuchsia, 0))
plot(rsiSMA, "RSI SMA", color.new(color.yellow, 0))
hline(50, "50 Midline", color=color.new(color.gray, 50))

// Plotting background for signals
bullishColor = color.new(color.green, 90)
bearishColor = color.new(color.red, 90)
bgcolor(bullishDivergence ? bullishColor : na, title="Bullish Divergence Zone")
bgcolor(bearishDivergence ? bearishColor : na, title="Bearish Divergence Zone")

// === EXPLANATION OF CONCEPTS ===
// Deep Knowledge of Market from AI:
// This indicator is based on a powerful, yet often misunderstood, concept: divergence.
// While standard divergence signals a potential trend reversal, hidden divergence signals a
// continuation of the prevailing trend. This is crucial for traders who want to capitalize
// on the momentum of a move rather than trying to catch tops and bottoms.

// Hidden Bullish Divergence: Occurs in an uptrend when price makes a higher low, but the
// RSI makes a lower low. This suggests that while there was a brief period of weakness, the
// underlying buying pressure is returning to push the trend higher. It’s a "re-energizing"
// of the bullish momentum.

// Hidden Bearish Divergence: Occurs in a downtrend when price makes a lower high, but the
// RSI makes a higher high. This indicates that while the sellers paused, the underlying
// selling pressure remains strong and is likely to continue pushing the price down. It's a
// subtle signal that the bears are regaining control.

// Combining Divergence with S/R: The true power of this indicator comes from its
// "confluence" principle. A divergence signal alone can be noisy. By requiring it to occur
// at a key support or resistance level (identified using pivot points), we are filtering
// out weaker signals and only focusing on high-probability setups where the market is
// likely to respect a previous area of interest. This tells us that not only is the trend
// likely to continue, but it is doing so from a strategic, well-defined point on the chart.

// Dynamic Take-Profit Targets: The take-profit targets are based on the Average True Range (ATR).
// ATR is a measure of market volatility. Using it to set targets ensures that your profit
// levels are dynamic and adapt to current market conditions. In a volatile market, your
// targets will be wider, while in a calm market, they will be tighter, helping you avoid
// unrealistic expectations and improving your risk management.

Clause de non-responsabilité

Les informations et les publications ne sont pas destinées à être, et ne constituent pas, des conseils ou des recommandations en matière de finance, d'investissement, de trading ou d'autres types de conseils fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.