BuyLow SellHigh Bands | ProjectSyndicate________________________________________
📊 BuyLow SellHigh (BLSH) Bands
Comprehensive Trading Guide – by ProjectSyndicate
________________________________________
🔰 1. Introduction
The BuyLow SellHigh (BLSH) Bands indicator is a powerful technical analysis tool designed for the TradingView platform. Works with any symbol. Gold/FX/indices/oil/crypto/stocks.
It provides traders with a clear, visual representation of:
• 📈 Overbought conditions
• 📉 Oversold conditions
This makes it easier to identify high-probability entry and exit points.
The indicator is built on:
• Dynamic price channels
• Fibonacci-based zones
• Color-coded market structure
💡 While the BLSH Bands can be used on Forex, Crypto, and Futures, this guide focuses on Gold (XAUUSD) using:
• M5
• M15
• M30 timeframes
________________________________________
🧠 2. Core Concepts
The BLSH Bands structure is created using two key components:
________________________________________
📐 Dynamic Price Bands
• Upper and lower bands are calculated using the highest high and lowest low
• Based on a user-defined lookback period (fiboPeriod)
• Reflects recent volatility and price range
This creates a self-adjusting channel that adapts to market conditions.
________________________________________
🧮 Fibonacci Zones
The space between the bands is divided into six Fibonacci-based zones:
• 0.786
• 0.618
• 0.500
• 0.382
• 0.214
⚠️ These are not traditional retracements — they are used to grade price extremity within the channel.
________________________________________
🎨 Color-Coded Zones Overview
Zone (Fib Level) Color Market Condition Interpretation
1.000 – 0.786 🔴 Red Extreme Overbought High reversal / pullback probability
0.786 – 0.618 🟠 Orange Overbought Selling pressure building
0.618 – 0.500 🟡 Yellow Mildly Overbought Bullish momentum weakening
0.500 – 0.382 🟢 Aqua Mildly Oversold Bearish momentum weakening
0.382 – 0.214 🔵 Deep Sky Blue Oversold Strong buying interest
0.214 – 0.000 🔷 Blue Extreme Oversold High bounce / reversal probability
🖤 Solid black separator lines ensure clean visual separation between zones for precise price location.
________________________________________
🪙 3. Trading Strategies for XAUUSD (Gold)
Gold’s volatility and respect for technical levels make it ideal for BLSH Bands strategies.
________________________________________
⚡ M5 Timeframe – Scalping Strategy
Designed for fast mean-reversion trades from extreme zones.
🟢 BUY Setup
• Price enters Extreme Oversold (Blue) zone
• Bullish confirmation candle appears:
o Hammer
o Bullish engulfing
• Enter BUY
🔴 SELL Setup
• Price enters Extreme Overbought (Red) zone
• Bearish confirmation candle appears:
o Shooting star
o Bearish engulfing
• Enter SELL
🎯 Take Profit:
• Median band (between Yellow & Aqua)
🛑 Stop Loss:
• Just outside the outer band
________________________________________
📆 M15 Timeframe – Day Trading Strategy
Balanced timeframe for higher-probability reversals.
🟢 BUY Setup
• Price enters Oversold (Blue / Deep Sky Blue)
• Strong bullish reversal candle closes back inside bands
• Enter BUY after close
🔴 SELL Setup
• Price enters Overbought (Red / Orange)
• Bearish reversal candle closes back inside bands
• Enter SELL after close
🎯 Take Profit (Multi-Target):
1. Median band
2. Opposite extreme band
🛑 Stop Loss:
• Beyond high/low of confirmation candle
________________________________________
🔄 M30 Timeframe – Swing Trading Strategy
Used for identifying major swing points.
🔍 Trend Filter
• Use 100 or 200 EMA
• Trade only in trend direction
🟢 Uptrend
• Buy pullbacks into Oversold zones
🔴 Downtrend
• Sell rallies into Overbought zones
📉 Confirmation:
• Band rejection
• RSI or MACD divergence
🎯 Take Profit:
• Previous structure levels
• Opposite band extreme
🛑 Stop Loss:
• Below / above recent swing high or low
________________________________________
🚨 4. Alerts System
Alerts are disabled by default to keep charts clean.
✅ How to Enable
• Open indicator settings
• Check “Enable Alerts”
________________________________________
🔔 Available Alerts
🔴 Overbought Alert
• Trigger: Price crosses above 0.786
• Message:
🔴 SELL SIGNAL: Price entered Overbought Zone – Consider selling or taking profits
🟢 Oversold Alert
• Trigger: Price crosses below 0.214
• Message:
🟢 BUY SIGNAL: Price entered Oversold Zone – Consider buying or entering long
________________________________________
⏱ Alert Spacing Logic
• Default: 20/50 bars
• Prevents repeated alerts in choppy markets
• Filters for higher-quality signals
________________________________________
⚙️ 5. Customization Settings
Adjust the indicator in the Settings panel:
🔧 Core Inputs
• fiboPeriod → Band sensitivity
• extremes → Price source (High/Low or Close)
🔔 Alert Controls
• Enable / disable alerts
• Separate control for overbought & oversold
• Alert spacing (bars)
________________________________________
⭐ How You Can Support ProjectSyndicate (3 Steps)
1. ✅ Click “Add to Favorites” to save this script to your TradingView Favorites
2. 🔎 Check out our other scripts to complete your SMC toolkit
3. 👤 Follow ProjectSyndicate for the latest updates, upgrades, and new releases
________________________________________
⚠️ 6. Disclaimer
Trading involves significant risk and may not be suitable for all traders.
This indicator is a decision-support tool, not a standalone trading system.
Always apply:
• Proper risk management
• Additional confirmations
• Sound trading discipline
📉 Past performance does not guarantee future results.
Formacje wykresów
[codapro] Elite Momentum & Smart Money Detector
Elite Momentum & Smart Money Detector
Overview
The Elite Detector is a non-repainting indicator that merges Smart Money Concepts, Adaptive Volatility-Based Momentum, and Multi-Timeframe Trend Confluence to identify high-probability trade setups. This tool helps confirm institutional intent and market pressure before triggering actionable signals.
Core Systems
Smart Money Concepts (SMC)
• Highlights institutional order blocks
• Detects equal highs/lows as liquidity zones
• Automatically cleans up outdated zones for clarity
Adaptive Momentum Engine
• Momentum calculated with volatility-adjusted smoothing
• Normalized scale from -100 to +100
• Candle coloring reflects trend strength dynamically
Squeeze Detection System
• Flags volatility contraction zones using Bollinger and Keltner channels
• Background shading highlights compression zones
• Histogram shows directional breakout pressure
Multi-Timeframe Trend Validation
• Aligns signals with higher timeframe momentum
• Built-in logic auto-selects appropriate HTF per chart
• Reduces false signals and improves timing
Signal Logic
Buy Signal appears when:
Momentum crosses from negative to positive
Squeeze condition is active
Higher timeframe confirms bullish trend
Sell Signal appears when:
Momentum crosses from positive to negative
Squeeze condition is active
Higher timeframe confirms bearish trend
All signals are non-repainting and appear only once all conditions are met.
Visual Dashboard (Top-Right Corner)
Displays real-time confirmation across five categories:
Momentum: Current trend direction and strength
Squeeze: Indicates if volatility is compressed
HTF Trend: Confirms higher-timeframe alignment
Volatility: Current volatility phase (low, normal, or high)
Signal Status: Buy, Sell, or Neutral (Wait)
Chart Visuals
Candle Colors:
• Bright green/red = Strong momentum
• Faded green/red = Weak momentum
Background Colors:
• Orange = Squeeze is active
• Clear = Normal market activity
Boxes:
• Green = Bullish order blocks
• Red = Bearish order blocks
Dashed Lines:
• Red = Equal highs (liquidity zones above)
• Green = Equal lows (liquidity zones below)
Alert Conditions
Includes three prebuilt alerts for automation and webhook systems:
Elite Buy Signal
Elite Sell Signal
Squeeze Activation
These alerts allow users to respond to market shifts in real time or integrate with automated trading workflows.
Best Practices
Wait for Confluence: Confirm all three systems (momentum, squeeze, HTF trend) before entering
Watch Order Blocks: Institutional zones often act as support/resistance
Monitor Liquidity Zones: Be cautious of stop hunts near equal highs/lows
Use Dashboard Cues: Let the HUD validate your setup
Always Use Risk Management: This tool increases probability, not certainty
Example Setup:
1. Squeeze background appears
2. Buy signal triangle confirms
3. Dashboard shows: Momentum strong up, Squeeze on, HTF trend up
4. Price bounces off green order block
→ High-probability long entry
Why It Works
This tool leverages multiple uncorrelated concepts to filter low-quality trades and highlight setups with real institutional backing:
Order Blocks and Liquidity Zones track smart money footprints
Volatility-adjusted Momentum captures real energy shifts
Multi-Timeframe Confluence confirms trades in the broader context
Non-repainting signals ensure reliability
Final Note
The Elite Detector is designed to show you:
Where smart money is positioned,
When the market is coiling for a move,
and Which direction is supported by momentum and trend.
Use it as your high-probability entry engine — across any market or timeframe.
Disclaimer
This tool was created using the CodaPro Pine Script architecture engine — designed to produce robust trading overlays, educational visuals, and automation-ready alerts. It is provided strictly for educational purposes and does not constitute financial advice. Always backtest and demo before applying to real capital.
High Volume S/R + VPA Entries + Broken Level Cleanup High Volume S/R + VPA Entries + Broken Level Cleanup
BBMA By K1M4K-ID- Final Validated Re-Entry//@version=6
indicator("BBMA By K1M4K-ID- Final Validated Re-Entry", overlay=true, max_labels_count=500)
// === INPUT BB ===
lengthBB = input.int(20, title="BB Period")
devBB = input.float(2.0, title="Deviation")
src = input.source(close, title="Source")
bbColorMid = input.color(color.purple, title="Mid BB Color")
bbColorTop = input.color(color.purple, title="Top BB Color")
bbColorLow = input.color(color.purple, title="Low BB Color")
showFill = input.bool(true, title="Show BB Fill")
showReEntrySignals = input.bool(true, "Show Re-Entry Signals (✅)")
showSignalTable = input.bool(true, "Show Signal Table")
// === BB CALCULATION ===
basis = ta.sma(src, lengthBB)
dev = devBB * ta.stdev(src, lengthBB)
topBB = basis + dev
lowBB = basis - dev
// === PLOT BB ===
pMid = plot(basis, title="Mid BB", color=bbColorMid, linewidth=2)
pTop = plot(topBB, title="Top BB", color=bbColorTop, linewidth=2)
pLow = plot(lowBB, title="Low BB", color=bbColorLow, linewidth=2)
fill(pTop, pLow, color=showFill ? color.new(color.purple, 85) : na, title="BB Fill")
// === INPUT MA SETTING ===
ma_func(source, length) => ta.wma(source, length)
// === MA HIGH/LOW ===
ma5_high = ma_func(high, 5)
ma10_high = ma_func(high, 10)
ma5_low = ma_func(low, 5)
ma10_low = ma_func(low, 10)
// === PLOT MA ===
p_ma5_high = plot(ma5_high, title="MA 5 High", color=color.green, linewidth=2)
p_ma10_high = plot(ma10_high, title="MA 10 High", color=color.green, linewidth=2)
fill(p_ma5_high, p_ma10_high, color=color.new(color.green, 85), title="MA High Fill")
p_ma5_low = plot(ma5_low, title="MA 5 Low", color=color.red, linewidth=2)
p_ma10_low = plot(ma10_low, title="MA 10 Low", color=color.red, linewidth=2)
fill(p_ma5_low, p_ma10_low, color=color.new(color.red, 85), title="MA Low Fill")
// === EMA 50 ===
ema50 = ta.ema(close, 50)
plot(ema50, title="EMA 50", color=color.blue, linewidth=3)
// === CSA KUKUH (LOGIKA ASLI LU - TIDAK DIUBAH) ===
var bool hasCsaBuy = false
var bool hasCsaSell = false
isCsaKukuhBuy = close > ma5_high and close > ma10_high and close > basis
isCsaKukuhSell = close < ma5_low and close < ma10_low and close < basis
if isCsaKukuhBuy and not hasCsaBuy
hasCsaBuy := true
hasCsaSell := false
else if isCsaKukuhSell and not hasCsaSell
hasCsaSell := true
hasCsaBuy := false
showCsaBuy = isCsaKukuhBuy and not hasCsaBuy
showCsaSell = isCsaKukuhSell and not hasCsaSell
plotshape(showCsaBuy, title="CSA Kukuh Buy First", location=location.belowbar, color=color.green, style=shape.labelup, text="CSAK", textcolor=color.white, size=size.small)
plotshape(showCsaSell, title="CSA Kukuh Sell First", location=location.abovebar, color=color.red, style=shape.labeldown, text="CSAK", textcolor=color.white, size=size.small)
// === CSM (HANYA SAAT KELUAR DARI DALAM BB) ===
wasInsideBB = (close >= lowBB and close <= topBB )
csmBuySignal = wasInsideBB and close > topBB
csmSellSignal = wasInsideBB and close < lowBB
plotshape(csmBuySignal, title="CSM Buy", location=location.abovebar, color=color.green, style=shape.triangleup, text="CSM", size=size.tiny)
plotshape(csmSellSignal, title="CSM Sell", location=location.belowbar, color=color.red, style=shape.triangledown, text="CSM", size=size.tiny)
// === CSA (BREAKOUT TANPA MELEWATI MID BB) ===
isCsaBuy = close > ma5_high and close > ma10_high and close <= basis
isCsaSell = close < ma5_low and close < ma10_low and close >= basis
plotshape(isCsaBuy, title="CSA Buy", location=location.belowbar, color=color.new(color.green, 60), style=shape.circle, text="CSA", size=size.tiny)
plotshape(isCsaSell, title="CSA Sell", location=location.abovebar, color=color.new(color.red, 60), style=shape.circle, text="CSA", size=size.tiny)
// === EXTREME ===
basis_ext = ta.sma(close, 20)
dev_ext = 2 * ta.stdev(close, 20)
isExtremeBuy() => ta.wma(low, 5) < basis_ext - dev_ext
isExtremeSell() => ta.wma(high, 5) > basis_ext + dev_ext
plotshape(isExtremeBuy(), title="Extreme Buy", location=location.belowbar, color=color.green, style=shape.labelup, text="E", size=size.tiny, textcolor=color.white)
plotshape(isExtremeSell(), title="Extreme Sell", location=location.abovebar, color=color.red, style=shape.labeldown, text="E", size=size.tiny, textcolor=color.white)
// === ZZL MA ===
isZzlBuy = (ma5_high > basis and ma10_high > basis and ma5_low > basis and ma10_low > basis and
(ma5_high <= basis or ma10_high <= basis or ma5_low <= basis or ma10_low <= basis))
isZzlSell = (ma5_high < basis and ma10_high < basis and ma5_low < basis and ma10_low < basis and
(ma5_high >= basis or ma10_high >= basis or ma5_low >= basis or ma10_low >= basis))
var bool zzlBuyShown = false
var bool zzlSellShown = false
if isZzlBuy and not zzlBuyShown
label.new(bar_index, low, "Z", style=label.style_label_up, color=color.green, textcolor=color.white)
zzlBuyShown := true
if not isZzlBuy
zzlBuyShown := false
if isZzlSell and not zzlSellShown
label.new(bar_index, high, "Z", style=label.style_label_down, color=color.red, textcolor=color.white)
zzlSellShown := true
if not isZzlSell
zzlSellShown := false
// ===========================================
// === VALIDASI + RE-ENTRY (H4 & H1) ===
// ===========================================
// --- Ambil data ---
= request.security(syminfo.tickerid, "240", )
wasInside_h4 = request.security(syminfo.tickerid, "240", (close >= (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB) ) and close <= (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB) )))
csmBuy_h4 = wasInside_h4 and request.security(syminfo.tickerid, "240", close > (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB)))
csmSell_h4 = wasInside_h4 and request.security(syminfo.tickerid, "240", close < (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB)))
csakBuy_h4 = close_h4 > ma5h_h4 and close_h4 > ma10h_h4 and close_h4 > basis_h4
csakSell_h4 = close_h4 < ma5l_h4 and close_h4 < ma10l_h4 and close_h4 < basis_h4
csaBuy_h4 = close_h4 > ma5h_h4 and close_h4 > ma10h_h4 and close_h4 <= basis_h4
csaSell_h4 = close_h4 < ma5l_h4 and close_h4 < ma10l_h4 and close_h4 >= basis_h4
csmBuy_h1 = request.security(syminfo.tickerid, "60", (close >= (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB) ) and close <= (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB) )) and close > (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB)))
csmSell_h1 = request.security(syminfo.tickerid, "60", (close >= (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB) ) and close <= (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB) )) and close < (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB)))
csakBuy_h1 = request.security(syminfo.tickerid, "60", close > ta.wma(high,5) and close > ta.wma(high,10) and close > ta.sma(close, lengthBB))
csakSell_h1 = request.security(syminfo.tickerid, "60", close < ta.wma(low,5) and close < ta.wma(low,10) and close < ta.sma(close, lengthBB))
csaBuy_h1 = request.security(syminfo.tickerid, "60", close > ta.wma(high,5) and close > ta.wma(high,10) and close <= ta.sma(close, lengthBB))
csaSell_h1 = request.security(syminfo.tickerid, "60", close < ta.wma(low,5) and close < ta.wma(low,10) and close >= ta.sma(close, lengthBB))
csmBuy_m15 = request.security(syminfo.tickerid, "15", close > (ta.sma(close, lengthBB) + devBB * ta.stdev(close, lengthBB)))
csmSell_m15 = request.security(syminfo.tickerid, "15", close < (ta.sma(close, lengthBB) - devBB * ta.stdev(close, lengthBB)))
csakBuy_d = request.security(syminfo.tickerid, "D", close > ta.wma(high,5) and close > ta.wma(high,10) and close > ta.sma(close, lengthBB))
csakSell_d = request.security(syminfo.tickerid, "D", close < ta.wma(low,5) and close < ta.wma(low,10) and close < ta.sma(close, lengthBB))
csaBuy_d = request.security(syminfo.tickerid, "D", close > ta.wma(high,5) and close > ta.wma(high,10) and close <= ta.sma(close, lengthBB))
csaSell_d = request.security(syminfo.tickerid, "D", close < ta.wma(low,5) and close < ta.wma(low,10) and close >= ta.sma(close, lengthBB))
// --- Validasi ---
validCsakH4Buy = csakBuy_h4 and ta.highest(csmBuy_h1 ? 1 : 0, 4) == 1
validCsakH4Sell = csakSell_h4 and ta.highest(csmSell_h1 ? 1 : 0, 4) == 1
validCsakH1Buy = csakBuy_h1 and ta.highest(csmBuy_m15 ? 1 : 0, 4) == 1
validCsakH1Sell = csakSell_h1 and ta.highest(csmSell_m15 ? 1 : 0, 4) == 1
validCsmH1Buy = csmBuy_h1 and (csaBuy_h4 or csakBuy_h4) and ta.highest(csmBuy_m15 ? 1 : 0, 4) == 1
validCsmH1Sell = csmSell_h1 and (csaSell_h4 or csakSell_h4) and ta.highest(csmSell_m15 ? 1 : 0, 4) == 1
validCsmH4Buy = csmBuy_h4 and (csaBuy_d or csakBuy_d) and ta.highest(csmBuy_h1 or csmSell_h1 ? 1 : 0, 4) == 1
validCsmH4Sell = csmSell_h4 and (csaSell_d or csakSell_d) and ta.highest(csmBuy_h1 or csmSell_h1 ? 1 : 0, 4) == 1
// --- Re-Entry Area ---
inReEntryBuy = low <= math.max(ma5_low, ma10_low)
inReEntrySell = high >= math.min(ma5_high, ma10_high)
// --- Flag Valid + Hit Detection ---
var bool vCsakH4B = false, vCsakH4S = false
var bool vCsakH1B = false, vCsakH1S = false
var bool vCsmH4B = false, vCsmH4S = false
var bool vCsmH1B = false, vCsmH1S = false
var bool hitCsakH4B = false, hitCsakH4S = false
var bool hitCsakH1B = false, hitCsakH1S = false
var bool hitCsmH4B = false, hitCsmH4S = false
var bool hitCsmH1B = false, hitCsmH1S = false
// Reset hit setiap candle
hitCsakH4B := false
hitCsakH4S := false
hitCsakH1B := false
hitCsakH1S := false
hitCsmH4B := false
hitCsmH4S := false
hitCsmH1B := false
hitCsmH1S := false
// Aktifkan flag saat valid
vCsakH4B := validCsakH4Buy ? true : vCsakH4B
vCsakH4S := validCsakH4Sell ? true : vCsakH4S
vCsakH1B := validCsakH1Buy ? true : vCsakH1B
vCsakH1S := validCsakH1Sell ? true : vCsakH1S
vCsmH4B := validCsmH4Buy ? true : vCsmH4B
vCsmH4S := validCsmH4Sell ? true : vCsmH4S
vCsmH1B := validCsmH1Buy ? true : vCsmH1B
vCsmH1S := validCsmH1Sell ? true : vCsmH1S
// Deteksi & reset saat re-entry
if vCsakH4B and inReEntryBuy
hitCsakH4B := true
vCsakH4B := false
if vCsakH4S and inReEntrySell
hitCsakH4S := true
vCsakH4S := false
if vCsakH1B and inReEntryBuy
hitCsakH1B := true
vCsakH1B := false
if vCsakH1S and inReEntrySell
hitCsakH1S := true
vCsakH1S := false
if vCsmH4B and inReEntryBuy
hitCsmH4B := true
vCsmH4B := false
if vCsmH4S and inReEntrySell
hitCsmH4S := true
vCsmH4S := false
if vCsmH1B and inReEntryBuy
hitCsmH1B := true
vCsmH1B := false
if vCsmH1S and inReEntrySell
hitCsmH1S := true
vCsmH1S := false
// --- Plot Re-Entry ---
//plotshape(showReEntrySignals and hitCsakH4B, location=location.belowbar, color=color.teal, style=shape.labelup, text="✅", size=size.normal)
//plotshape(showReEntrySignals and hitCsakH4S, location=location.abovebar, color=color.orange, style=shape.labeldown, text="✅", size=size.normal)
//plotshape(showReEntrySignals and hitCsakH1B, location=location.belowbar, color=color.green, style=shape.labelup, text="✅", size=size.small)
//plotshape(showReEntrySignals and hitCsakH1S, location=location.abovebar, color=color.red, style=shape.labeldown, text="✅", size=size.small)
//plotshape(showReEntrySignals and hitCsmH1B, location=location.belowbar, color=color.green, style=shape.labelup, text="✅ CSM", size=size.tiny)
//plotshape(showReEntrySignals and hitCsmH1S, location=location.abovebar, color=color.red, style=shape.labeldown, text="✅ CSM", size=size.tiny)
//plotshape(showReEntrySignals and hitCsmH4B, location=location.belowbar, color=color.teal, style=shape.labelup, text="✅ CSM", size=size.tiny)
//plotshape(showReEntrySignals and hitCsmH4S, location=location.abovebar, color=color.orange, style=shape.labeldown, text="✅ CSM", size=size.tiny)
// ===========================================
// === TABEL SIGNAL H1 & H4 (FINAL) ===
// ===========================================
var table sigTable = table.new(position.top_right, 4, 5, border_width=1)
if barstate.islast and showSignalTable
table.cell(sigTable, 0, 0, "TF", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 1, 0, "Signal", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 2, 0, "Status", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 3, 0, "Re-Entry", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 0, 1, "H4", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 1, 1, "CSAK Buy", text_color=color.green, bgcolor=color.new(color.green, 90))
table.cell(sigTable, 2, 1, vCsakH4B ? "✅ Valid" : "-", text_color=vCsakH4B ? color.green : color.gray, bgcolor=color.new(vCsakH4B ? color.green : color.gray, 90))
table.cell(sigTable, 3, 1, hitCsakH4B ? "✅ Hit" : "-", text_color=hitCsakH4B ? color.teal : color.gray, bgcolor=color.new(hitCsakH4B ? color.teal : color.gray, 90))
table.cell(sigTable, 0, 2, "H4", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 1, 2, "CSAK Sell", text_color=color.red, bgcolor=color.new(color.red, 90))
table.cell(sigTable, 2, 2, vCsakH4S ? "✅ Valid" : "-", text_color=vCsakH4S ? color.red : color.gray, bgcolor=color.new(vCsakH4S ? color.red : color.gray, 90))
table.cell(sigTable, 3, 2, hitCsakH4S ? "✅ Hit" : "-", text_color=hitCsakH4S ? color.orange : color.gray, bgcolor=color.new(hitCsakH4S ? color.orange : color.gray, 90))
table.cell(sigTable, 0, 3, "H1", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 1, 3, "CSM Buy", text_color=color.green, bgcolor=color.new(color.green, 90))
table.cell(sigTable, 2, 3, vCsmH1B ? "✅ Valid" : "-", text_color=vCsmH1B ? color.green : color.gray, bgcolor=color.new(vCsmH1B ? color.green : color.gray, 90))
table.cell(sigTable, 3, 3, hitCsmH1B ? "✅ Hit" : "-", text_color=hitCsmH1B ? color.teal : color.gray, bgcolor=color.new(hitCsmH1B ? color.teal : color.gray, 90))
table.cell(sigTable, 0, 4, "H1", text_color=color.white, bgcolor=color.black)
table.cell(sigTable, 1, 4, "CSM Sell", text_color=color.red, bgcolor=color.new(color.red, 90))
table.cell(sigTable, 2, 4, vCsmH1S ? "✅ Valid" : "-", text_color=vCsmH1S ? color.red : color.gray, bgcolor=color.new(vCsmH1S ? color.red : color.gray, 90))
table.cell(sigTable, 3, 4, hitCsmH1S ? "✅ Hit" : "-", text_color=hitCsmH1S ? color.orange : color.gray, bgcolor=color.new(hitCsmH1S ? color.orange : color.gray, 90))
SWING ATR BasedWhat does this indicator do?
1. It identifies Market Swings The script monitors price action to detect when a trend changes direction.
It uses ATR (Average True Range) to measure volatility, ensuring it doesn't get tricked by small, insignificant price movements.
To validate a change in direction (from bullish to bearish, or vice versa), it waits for the price to cover a specific distance (defined by the kRange parameter) and requires at least two significant candles.
2. It plots Support and Resistance zones As soon as a new high or low point is confirmed:
In Green (Bull): It draws a support line at the level of the last low.
In Red (Bear): It draws a resistance line at the level of the last high.
Auto-Cleaning: If the price breaks through a support line, the line turns gray and stops. The script only keeps active (unbroken) levels on the screen.
3. It calculates an "SGE Score" (Market State) This is the "brain" of the script. It assigns a rating to the current trend:
+2 (Bullish): The price has broken a resistance.
-2 (Bearish): The price has broken a support.
0 (Neutral): The market is indecisive (for example, after a break that contradicts the previous one).
Key Feature: This score has a "one-candle delay." It waits for the next candle to close before confirming a score change, which helps avoid reacting too quickly to false alerts.
4. It simplifies visual reading To keep your chart clean and readable:
It only highlights the 3 levels closest to the current price (those most likely to be hit soon).
It colors the chart candles directly: Green if the score is +2, Red if the score is -2, and Gray if it is neutral.
5. Dashboard In the top-right corner of your screen, it displays a permanent summary:
The current score (-2, 0, or 2).
The number of active supports and resistances.
Summary: This is a "smart" trend detector. Instead of just looking at whether the price is going up or down, it waits for the price to break important structural levels (confirmed by volatility) to tell you: "Caution, the structure has just shifted from bullish to bearish."
Recommended Settings:
kRange: 1.3 / 1.4
ATR Mult: 0.3 to 0.5
Script created with Claude AI.
Dynamic MTF Reversal Sequential [Realtime]SMA Reversal Sequential MTF Engine
Professional Pivot Identification & Squeeze Analysis
1. Overview
The SMA Reversal Sequential MTF Engine is a sophisticated environment recognition tool that monitors 8 timeframes (1m to Monthly) to identify objective Pivot Highs and Lows.
Unlike standard indicators that rely on simple price-crosses, this engine determines structural market turns based on the curvature (slope) of the SMA. By automating the detection of price consolidation (Squeeze) and synchronizing it with higher timeframe trends, it provides a systematic approach to capturing high-probability breakout opportunities.
2. Input Settings & Operations
Each parameter is designed to help you filter noise and focus on the market structure that suits your trading style.
■ Main Settings
Use Short Period:
ON: Uses (5, 3, 7) periods. Ideal for scalping. It identifies micro-pivots and sensitive trend shifts.
OFF: Uses (20, 6, 20) periods. Designed for Day/Swing trading. It filters out noise and focuses on major structural highs and lows.
Hide Lower Timeframes:
Automatically hides labels from timeframes shorter than your current chart (e.g., hiding 1m labels while on a 1H chart) to maintain a clean workspace.
Break Label Right Offset:
Adjusts the horizontal position of the "Breakout" price labels on the right side of the chart.
■ Drawing Options
Show Only Current TF Labels:
When enabled, it hides "15", "1H" labels from other timeframes on the chart. Note: The MTF Dashboard will still track all timeframes regardless of this setting.
Show Trendlines & Channels:
Plots lines connecting determined Pivot Highs and Lows, visualizing the current "Trading Range" or "Channel."
Show ZigZag Line:
Connects the confirmed Highs and Lows with straight lines, making "Market Structure" (Higher Highs / Lower Lows) instantly recognizable.
Hide Outer Channel on Squeeze:
During a Squeeze (consolidation), this hides older wide channels to highlight the immediate converging boundaries.
3. Core Logic: Determining Highs & Lows
This engine determines "Pivots" through a logical three-step process:
SMA Reversal Detection: The engine calculates when the SMA slope changes from down to up (or vice versa) using a sequential offset comparison.
Pivot Determination: Once an SMA turn is confirmed, the highest/lowest price point during that turn is determined as a structural Pivot High/Low.
Squeeze Identification: When the last two determined Highs are "Lower Highs" and the last two Lows are "Higher Lows," the engine identifies a Squeeze (Triangle Consolidation) and marks it with a Green Dot (●).
4. How to Trade (Step-by-Step)
Check the MTF Dashboard: Look at the top-right table. If the higher timeframes (4H, 1D) are Blue, the market is in a structural uptrend (making new Highs).
Wait for the Squeeze: Wait for the Green Dot (●) on your current timeframe. This signifies that energy is being stored within a tight range.
The Breakout Signal: When the price breaks the squeeze in the direction of the higher timeframe trend, a Rocket (🚀) or Lightning (⚡) icon appears. This is a high-probability entry point where a lower-timeframe consolidation resolves into a higher-timeframe trend.
5. Important Notes
As an SMA-based tool, it is a "Lagging Indicator" by nature. It focuses on structural confirmation rather than predicting unpredictable price spikes.
Always prioritize the MTF Dashboard colors. Trading against the higher timeframe trend is not recommended.
SMA Reversal Sequential MTF Engine
〜多時間軸SMA反転による高値安値確定と保合い分析〜
1. 概要 (Overview)
本スクリプトは、8つの時間軸(1分足〜月足)におけるSMA(単純移動平均線)の傾きを解析し、**「主観を排除した客観的な高値・安値」**を自動で決定するマルチタイムフレーム(MTF)環境認識エンジンです。
最大の特徴は、価格の上下に一喜一憂するのではなく、移動平均線という「相場の平均的な流れ」が反転したポイントを「真の節目(Pivot)」として定義する点にあります。これにより、ボラティリティの収束(スクイーズ)と、上位足に同期した高確率なブレイクアウトをシステマチックに捉えることができます。
2. インプット設定の完全解説 (Input Settings)
ユーザーが設定画面で調整できる各項目の具体的な意味と、変更による効果を解説します。
■ 基本設定 (Main Settings)
短期設定を使用 (Use Short Period):
ON: 期間 (5, 3, 7) を使用。スキャルピングや短期トレード向け。非常に細かく高値・安値を決定し、微細な反転も逃さず捉えます。
OFF: 期間 (20, 6, 20) を使用。デイトレード〜スイング向け。ノイズを排除し、主要な大きな波の高値・安値のみを決定します。
下位足を非表示 (Hide Lower Timeframes):
ON: 現在のチャートより短い足(例:1時間足を表示中に1分・5分足のサインなど)を隠します。上位足の構造把握に集中し、チャートをスッキリさせたい時に有効です。
ブレイク文字の右オフセット:
チャート右側の余白に表示される価格情報の位置を調整します。数値が大きいほど右側に移動します。
■ 表示設定 (Drawing Options)
現在足のラベルのみ表示 (Show Only Current TF Labels):
ON: チャート上の「15」「1H」といった他時間足のサインを非表示にします。
利点: 右上のダッシュボードには全情報が維持されるため、視認性を高めつつ、MTF分析の精度を維持できます。
トレンドライン&チャネル (Show Trendlines & Channels):
確定した高値同士・安値同士を線で結びます。現在の価格が「どの価格幅の範囲内(チャネル)」で推移しているかを可視化します。
ZigZagライン (Show ZigZag Line):
確定した高値と安値を交互に直線で結びます。ダウ理論的な「上昇・下落の波」の推移が一目で把握可能になります。
保合い中は外側ラインを非表示:
収束(スクイーズ)が発生した際、古い広いチャネルを隠し、今まさに機能している収束ラインのみを際立たせます。
3. 核心ロジック:高値・安値の決定プロセス
本ツールは以下の手順でチャート上の構造を構築します。
SMA反転の検知: SMAの傾きが「下落→上昇」または「上昇→下落」に転じた瞬間を計算。
節点の確定: その反転が起きた前後の最高値・最安値を**「確定した高値・安値」**として決定し、ラベルを打ちます。
スクイーズ判定: 決定された「直近2つの高値」が切り下がり、かつ「直近2つの安値」が切り上がった場合を**三角保合い(スクイーズ)**と定義し、緑のドット(●)を表示します。
4. 実戦的な操作フロー
このインジケーターを使ってどのようにトレードを組み立てるかの推奨ステップです。
環境認識 (Environment Check): 右上のダッシュボードで上位足(4H, 1D等)の色を確認。青なら「買いの高値更新中」、赤なら「売りの安値更新中」です。
保合い待機 (Squeeze Watching): 現在の足に**緑のドット(●)**が出るのを待ちます。これは決定された節目が収束し、次に大きく動くためのエネルギーを蓄積している合図です。
ブレイクの判断 (Decision): 保合いを抜けた際、ダッシュボードの上位足と同じ方向であれば、**🚀(ロケット)や⚡(稲妻)**のアイコンが出現します。これが「上位足の勢いに乗った、下位足の収束解消」という、最も期待値の高いエントリーポイントです。
5. 注意事項
本ツールは移動平均線に基づく「遅行指標」の性質を持ちます。そのため、急激なスパイク(一瞬の突発的な動き)には反応しない場合があります。
常に「上位足のトレンドがどちらを向いているか」をダッシュボードで確認し、逆張りでの使用は避けることを推奨します。
Order Blocks & Breaker Blocks Destek DirencOrder Blocks & Breaker Blocks Destek Direnc Al Sat Bölgeleri
Short-Term Weekly Refuges (Shelters)## // Introduction // (Spanish Texts Below)
═══════════════════════════
Short-Term Weekly Refuges (Shelters) (WR or RS) is a structural analysis indicator designed to track price action during the current week. It combines a configurable ZigZag with Fibonacci retracements anchored to recent phases, using the Weekly Opening Price (W.O.P.) as a key reference level.
This indicator is optimized for 4H timeframe but also works on 1H and 15min charts.
## // Theoretical Foundation of the Indicator //
═════════════════════════════════════════════════
The WR (RS) indicator provides a structural framework for following price action during the current trading week.
The core concept: Recent ZigZag phases, combined with the Weekly Opening Price, create dynamic support and resistance levels that institutional traders often monitor and use for intraweek positioning. The indicator allows you to select which recent phase (1-10) serves as the Fibonacci anchor.
## // Indicator Objectives //
═════════════════════════════
1) Display a configurable ZigZag showing recent price structure with numbered phases (1 = most recent). Users should configure the ZigZag parameters based on whether they are analyzing a Major Degree Pattern (larger swings, less noise) or a Minor Degree Pattern (smaller swings, more detail), following standard Elliott Wave terminology. Configure the ZigZag to match the degree of your analysis: use higher Depth values for Major Degree Patterns, or lower values for Minor Degree Patterns.
2) Draw Fibonacci retracements on a user-selected phase, with two modes:
• "On ZigZag": Traditional Fibonacci on the selected phase.
• "Relative to W.O.P.": Fibonacci from phase anchor (i0) to Weekly Opening Price.
3) Show Weekly Opening Price lines as horizontal references, with the current week's line extended into the future.
4) Provide Pivot Up/Down markers for additional confirmation of local highs and lows.
5) Support multiple simultaneous indicator loads with visual identifier labels to distinguish between different analysis degrees (e.g., "Major Degree Pattern" vs "Minor Degree Pattern").
6) Optional Embedded Indicator: Enable Intraday Shelters (RID) - percentage-based support/resistance levels calculated from the Daily Opening Price, useful for 1H and 15min trading.
## // Key Features //
═════════════════════
• **Flexible ZigZag**: Adjustable Depth, Deviation, and Backstep parameters to adapt to any asset's volatility and degree pattern.
• **Phase Selection**: Choose from the 10 most recent phases for Fibonacci anchoring.
• **Dual Fibonacci Modes**: Trace on the ZigZag phase itself, or relative to the Weekly Opening Price.
• **New Age Color Palette**: Professional Fibonacci color scheme used by old school experienced traders.
• **Weekly Opening Price (W.O.P.)**: Historical weekly opens plus current week projection.
• **"Show Only W.O.P." Mode**: Isolate just the Weekly Opening Price line for cleaner charts on non-4H timeframes.
• **Optional Intraday Shelters (RID)**: 11 percentage levels (±0.382%, ±1%, ±1.5%, ±2%, ±2.5%) based on Daily Opening Price.
• **Multi-Load Support**: Visual identifier tags and Large Label for running multiple indicator instances simultaneously.
## // Recommended Workflow //
═════════════════════════════
1) Load the indicator on a 4H chart.
2) Adjust ZigZag parameters (Depth, Deviation) until the phases match your visual analysis of recent price structure.
3) Select the phase you want to use as Fibonacci anchor (typically Phase 2, 3 or higher).
4) Choose Fibonacci mode: "On ZigZag" for phase analysis, or "Relative to W.O.P." for analysis based on weekly opening price context.
5) Monitor how price interacts with the Fibonacci levels and Weekly Opening Price throughout the week.
6) Optionally enable RID for intraday high precision order placements on 1H or 15min charts.
## // Integration with Other Refuge Indicators //
═════════════════════════════════════════════════
This indicator WR (RS) is part of our complete refuge-based analysis ecosystem:
• LTR (RLP) (Long-Term Refuges): For automatic determination of the predominant phase of a ZigZag, which institutional investors choose as the basis for a Fibo whose levels calculate the projection for order placement over the following months and years.
• LTRS (RLPS) (Simple Long-Term Refuges): Simplified version of LTR in which the known coordinates of the predominant phases (obtained with the LTR indicator) of up to five assets are easily captured for permanent long-term operation.
• WR (RS) (Short-Term Weekly Refuges): For short-term tactical analysis (4H, 1H) based on chosen phases of a ZigZag that define Fibo levels effective during the near past week(s).
• IDR (RID) (Intra-Day Refuges): For daily operations relying on intraday levels on timeframes of 1H or less. Ideal for scalping traders.
By combining LTR, LTRS, WR and IDR, you obtain a multi-level framework that allows you to operate with clarity at any time horizon, from intraday positions to investments spanning months and years.
## // Additional Notes //
═════════════════════════
1) Default parameters are optimized for volatile assets (crypto, tech stocks). For forex or less volatile instruments, consider reducing Deviation to 3-8%.
2) The "Phase in Development" (dashed line) shows the tentative current ZigZag segment that may still change as new bars form.
3) Due to TradingView's English-only publication rules, the complete Spanish version of this indicator with all tooltips and documentation will be available soon in our GitHub repository: aj-poolom-maasewal.
4) Bug reports, improvement proposals for the ZigZag generator, pattern determination, or Fibo composition, etc., will be greatly appreciated and taken into account for a future version. Best regards and happy hunting.
════════════════════════════════════════════════════
════════════════════════════════════════════════════
TEXTO EN ESPANIOL (Sin acentos ni enies para compatibilidad con TradingView)
════════════════════════════════════════════════════
## // Introduccion //
═════════════════════
Refugios Semanales (RS o WR) es un indicador de analisis estructural diseniado para seguir la accion del precio durante la semana en curso. Combina un ZigZag configurable con retrocesos de Fibonacci anclados a fases recientes, utilizando el Precio de Apertura Semanal (P.A.S.) como nivel de referencia clave.
Este indicador esta optimizado para temporalidad de 4H pero tambien funciona en graficos de 1H y 15min.
## // Fundamento Teorico del Indicador //
═════════════════════════════════════════
El indicador RS (WR) proporciona un marco estructural para seguir la accion del precio durante la semana de operacion actual.
El concepto central: Las fases recientes del ZigZag, combinadas con el Precio de Apertura Semanal, crean niveles dinamicos de soporte y resistencia que los operadores institucionales frecuentemente monitorean para su posicionamiento intrasemanal. El indicador permite seleccionar cual fase reciente (1-10) sirve como ancla del Fibonacci.
## // Objetivos del Indicador //
════════════════════════════════
1) Mostrar un ZigZag configurable con la estructura de precios reciente y fases numeradas (1 = mas reciente). Los usuarios deben configurar los parametros del ZigZag segun esten analizando una Pauta de Grado Mayor (oscilaciones mas amplias, menos ruido) o una Pauta de Grado Menor (oscilaciones mas pequenias, mas detalle), siguiendo la terminologia estandar de Ondas de Elliott. Configure el ZigZag para que coincida con el grado de su analisis: use valores de Profundidad mas altos para Pautas de Grado Mayor, o valores mas bajos para Pautas de Grado Menor.
2) Dibujar retrocesos de Fibonacci en una fase seleccionada por el usuario, con dos modos:
• "En el ZigZag": Fibonacci tradicional sobre la fase seleccionada.
• "Respecto al P.A.S.": Fibonacci desde el ancla de la fase (i0) hasta el Precio de Apertura Semanal.
3) Mostrar lineas del Precio de Apertura Semanal como referencias horizontales, con la linea de la semana actual extendida hacia el futuro.
4) Proporcionar marcadores de Pivote Arriba/Abajo para confirmacion adicional de maximos y minimos locales.
5) Soportar multiples cargas simultaneas del indicador con etiquetas identificadoras visuales para distinguir entre diferentes grados de analisis (ej: "Pauta de Grado Mayor" vs "Pauta de Grado Menor").
6) Indicador Integrado Opcional: Habilitar Refugios Intra-Diarios (RID) - niveles de soporte/resistencia basados en porcentajes calculados desde el Precio de Apertura Diaria, util para operacion en 1H y 15min.
## // Caracteristicas Principales //
════════════════════════════════════
• **ZigZag Flexible**: Parametros ajustables de Profundidad, Desviacion y Retroceso para adaptarse a la volatilidad y grado de pauta de cualquier activo.
• **Seleccion de Fase**: Elija entre las 10 fases mas recientes para el anclaje del Fibonacci.
• **Modos Duales de Fibonacci**: Trace sobre la fase del ZigZag, o relativo al Precio de Apertura Semanal.
• **Paleta de Colores New Age**: Esquema de colores profesional de Fibonacci usado por operadores institucionales de la vieja escuela.
• **Precio de Apertura Semanal (P.A.S.)**: Aperturas semanales historicas mas proyeccion de la semana actual.
• **Modo "Solo P.A.S."**: Aisla unicamente la linea del Precio de Apertura Semanal para graficos mas limpios en temporalidades distintas a 4H.
• **Refugios Intra-Diarios Opcionales (RID)**: 11 niveles porcentuales (±0.382%, ±1%, ±1.5%, ±2%, ±2.5%) basados en el Precio de Apertura Diaria.
• **Soporte Multi-Carga**: Etiquetas identificadoras visuales y Rotulo Grande para ejecutar multiples instancias del indicador simultaneamente.
## // Flujo de Trabajo Recomendado //
═════════════════════════════════════
1) Cargue el indicador en un grafico de 4H.
2) Ajuste los parametros del ZigZag (Profundidad, Desviacion) hasta que las fases coincidan con su analisis visual de la estructura de precios reciente.
3) Seleccione la fase que desea usar como ancla del Fibonacci (tipicamente Fase 2, 3 o superior).
4) Elija el modo de Fibonacci: "En el ZigZag" para analisis de fase, o "Respecto al P.A.S." para analisis basado en el contexto del precio de apertura semanal.
5) Monitoree como el precio interactua con los niveles de Fibonacci y el Precio de Apertura Semanal durante la semana.
6) Opcionalmente habilite RID para precision intradiaria en graficos de 1H o 15min.
## // Integracion con Otros Indicadores de Refugios //
══════════════════════════════════════════
RS (WR) es parte de nuestro ecosistema completo de analisis basado en refugios:
• RLP (LTR) (Refugios de Largo Plazo): Para determinacion automatica de la fase preponderante de un ZigZag, que los inversionistas institucionales eligen como base para un Fibo cuyos niveles calculan la proyeccion para colocacion de ordenes durante los meses y anios siguientes.
• RLPS (LTRS) (Refugios de Largo Plazo Simplificado): Version simplificada de RLP en la cual las coordenadas conocidas de las fases preponderantes (obtenidas con el indicador RLP) de uno o hasta cinco activos se capturan facilmente para operacion permanente de largo plazo.
• RS (WR) (Refugios Semanales de Corto Plazo): Para analisis tactico de corto plazo (4H, 1H) basado en fases elegidas de un ZigZag que definen niveles Fibo efectivos durante la(s) semana(s) pasada(s) reciente(s).
• RID (IDR) (Refugios Intra-Diarios): Para operaciones diarias basadas en niveles intradiarios en temporalidades de 1H o menos. Ideal para operadores de scalping.
Al combinar RLP, RLPS, RS y RID, obtiene un marco multinivel que le permite operar con claridad en cualquier horizonte temporal, desde posiciones intradiarias hasta inversiones que abarcan meses y anios.
## // Notas Adicionales //
══════════════════════════
1) Los parametros por defecto estan optimizados para activos volatiles (cripto, acciones tecnologicas). Para forex o instrumentos menos volatiles, considere reducir la Desviacion a 3-8%.
2) La "Fase en Desarrollo" (linea discontinua) muestra el segmento tentativo actual del ZigZag que aun puede cambiar conforme se formen nuevas barras.
3) Debido a las reglas de publicacion de TradingView (solo ingles), la version completa en espaniol de este indicador con todos los tooltips y documentacion estara disponible proximamente en nuestro repositorio de GitHub: aj-poolom-maasewal.
4) El reporte de cualquier error encontrado, propuestas de mejoras al generador de Zigzags, determinacion de pautas, o composicion del Fibo, etc., seran ampliamente agradecidas y tomadas en cuenta para una proxima version. Saludos y buena caceria.
══════════════════════════════════════════════════
Smart Floors & Ceilings [RSI + Volume] - MarcDuckMarks floors and ceilings based off of RSI and Volume
HADYAN NEW SCALPING V 2.9//@version=5
indicator(title='HADYAN NEW SCALPING V 2.9', overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ====================================================================================================
// BAGIAN 1: PENGATURAN UTAMA & LOGIKA INTI
// ====================================================================================================
styleGroup = 'Gaya Trading (Trading Style)'
tradingStyle = input.string('Mencuri Profit', title='Pilih Gaya Trading', options= , group=styleGroup)
// --- FITUR ANTI-KEDIP ---
useConfirmedBar = input.bool(true, title='✅ Sinyal Anti-Kedip (Tunggu Close)?', group=styleGroup)
a_custom = input.float(1.0, title='Key Value (Custom)', group=styleGroup)
c_custom = input.int(10, title='ATR Period (Custom)', group=styleGroup)
var float a = 1.0
var int c = 10
// Variabel filter internal
var bool _useEmaFilter = false
var bool _useRsiFilter = false
var bool _useCandleFilter = false
var bool _useVolumeFilter = false
var bool _useAdxFilter = false
var bool _useSnrFilter = false
miscGroup = 'Pengaturan Filter (Tanpa Ghost)'
waspadaFactor = input.float(0.75, title='Waspada - Faktor Jarak ATR', group=miscGroup)
tamakFactor = input.float(3.0, title='Jangan Tamak - Faktor Jarak ATR', group=miscGroup)
// --- FILTER TREN (EMA) ---
useEmaFilter = input.bool(false, title='Gunakan Filter Tren EMA Cross?', group=miscGroup)
emaFastLen = input.int(21, title='Periode EMA Cepat', group=miscGroup)
emaSlowLen = input.int(50, title='Periode EMA Lambat', group=miscGroup)
mtfTimeframe = input.string('15', title='Timeframe MTF', group=miscGroup)
// --- FILTER MOMENTUM ---
useRsiFilter = input.bool(false, title='Gunakan Filter Momentum RSI?', group=miscGroup)
rsiFilterLen = input.int(14, title='Periode RSI', group=miscGroup)
rsiBuyLevel = input.float(50.0, title='RSI Buy Level (Min)', group=miscGroup)
rsiSellLevel = input.float(50.0, title='RSI Sell Level (Max)', group=miscGroup)
rsiReversalLevel = input.float(70.0, title='RSI Reversal Level (70/30)', group=miscGroup)
// --- FILTER LAIN ---
useCandleFilter = input.bool(false, title='Gunakan Filter Pola Candlestick?', group=miscGroup)
useVolumeFilter = input.bool(false, title='Gunakan Filter Volume?', group=miscGroup)
volumeLen = input.int(20, title='Periode Volume MA', group=miscGroup)
volumeThreshold = input.float(0.3, title='Min. Volume Factor', group=miscGroup)
// --- FILTER SNR ---
useSnrFilter = input.bool(false, title='Gunakan Filter Support/Resistance (SNR)?', group=miscGroup)
snrLookback = input.int(10, title='Pivot Lookback (SNR)', group=miscGroup)
snrDistanceFactor = input.float(2.0, title='Jarak Max ke S/R (xATR)', group=miscGroup)
// --- FILTER ADX ---
useAdxFilter = input.bool(false, title='Gunakan Filter Kondisi Pasar (ADX)?', group=miscGroup)
adxLen = input.int(14, title='Periode ADX', group=miscGroup)
adxMinLevel = input.float(15.0, title='ADX Min. Level', group=miscGroup)
// ** PENGATURAN MANAJEMEN RISIKO **
riskGroup = 'Manajemen Risiko'
useAutoBreakeven = input.bool(true, title='Gunakan Auto Breakeven?', group=riskGroup)
breakevenFactor = input.float(1.0, title='Breakeven Factor (Dalam R/ATR)', group=riskGroup)
// ==============================================
// --- INPUT FITUR TAMBAHAN ---
// ==============================================
meterGroup = 'Visual & Tambahan'
showCandlePanel = input.bool(true, title='Tampilkan Panel Info Candle?', group=meterGroup)
showCandleArrows = input.bool(false, title='Tampilkan Panah Tiap Candle?', group=meterGroup)
// ==============================================
// --- FITUR UPGRADE ---
// ==============================================
upgradeGroup = '🔥 Fitur Upgrade'
useConfirmFilter = input.bool(false, title=' Gunakan Konfirmasi Momentum (MidPoint)?', group=upgradeGroup)
useReversalExit = input.bool(false, title=' Gunakan Exit Cepat (Candle Pembalikan)?', group=upgradeGroup)
showReEntry = input.bool(true, title=' Tampilkan Sinyal Re-Entry (Add Position)?', group=upgradeGroup)
showAggressiveEMA = input.bool(false, title=' Tampilkan Sinyal Agresif (EMA Bounce)?', group=upgradeGroup)
emaAggressiveFastLen = input.int(9, title=' EMA Cepat (Agresif)', group=upgradeGroup)
emaAggressiveSlowLen = input.int(21, title=' EMA Lambat (Agresif)', group=upgradeGroup)
useBBTamak = input.bool(false, title=' Gunakan Target Profit Dinamis (BB)?', group=upgradeGroup)
bbLen = input.int(20, title=' Periode Bollinger Bands', group=upgradeGroup)
bbStdDev = input.float(2.0, title=' Deviasi Bollinger Bands', group=upgradeGroup)
showDashboard = input.bool(true, title=' Tampilkan Dashboard Pro?', group=upgradeGroup)
showAdvisorBubble = input.bool(true, title=' Tampilkan Gelembung Advisor di Chart?', group=upgradeGroup)
// --- BARU: ZONE INPUT ---
showSmartZones = input.bool(true, title=' Tampilkan Zona Buy/Sell (Supply/Demand)?', group=upgradeGroup)
zoneLookback = input.int(5, title=' Kekuatan Zona (Lookback Pivot)', group=upgradeGroup)
// ====================================================================================================
// BAGIAN UPGRADE: PIVOT, FIBO & STOCHASTIC (NEW)
// ====================================================================================================
pivotGroup = "Pivot, Fibo & Stoch (UPGRADE)"
// Pivot Inputs
showPivotPoints = input.bool(true, title='Tampilkan Daily Pivot (R1-S2)?', group=pivotGroup)
pivotColor = input.color(color.new(color.orange, 0), "Warna Garis Pivot Utama", group=pivotGroup)
// Fibo Inputs
showFiboLevels = input.bool(true, title='Tampilkan Fibo Retracement (CLEAN)?', group=pivotGroup)
fiboXOffset = input.int(10, title='Geser Fibo (X-Offset)', group=pivotGroup)
// Stochastic Inputs
showStochChart = input.bool(true, title='Tampilkan MINI CHART Stochastic (Realtime)?', group=pivotGroup)
stochWidth = input.int(30, title='Lebar Chart (Bars)', minval=10, maxval=100, group=pivotGroup)
// ==============================================
// --- DEKLARASI VAR GLOBAL ---
// ==============================================
var table infoPanel_m = table.new(position.bottom_center, 3, 2, border_width = 1, bgcolor = color.new(#363a45, 0))
var string finalDir_m = ""
var table dashboardPanel = table.new(position.top_right, 2, 10, border_width = 1, bgcolor = color.new(#363a45, 80))
var int rsiLen_actual = rsiFilterLen
var int adxLen_actual = adxLen
var string marketModeText = "..."
var color marketModeColor = color.gray
// ==============================================
// --- LOGIKA PEMILIHAN GAYA (ADAPTIF) ---
// ==============================================
if tradingStyle == 'Mencuri Profit'
a := 1.0
c := 10
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Scalping Cepat'
a := 0.8
c := 8
rsiLen_actual := 7
adxLen_actual := 10
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Swing Santai'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Sangat Akurat'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := true
_useRsiFilter := true
_useCandleFilter := true
_useVolumeFilter := true
_useAdxFilter := true
_useSnrFilter := true
else if tradingStyle == 'Custom'
a := a_custom
c := c_custom
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
// ==============================================
// --- LOGIKA INTI & PERHITUNGAN FILTER ---
// ==============================================
xATR = ta.atr(c)
nLoss = a * xATR
src = close
// --- FILTER TREN ---
emaFast = ta.ema(src, emaFastLen)
emaSlow = ta.ema(src, emaSlowLen)
bool emaCrossOkForBuy = close > emaSlow and emaFast > emaSlow
bool emaCrossOkForSell = close < emaSlow and emaFast < emaSlow
// OPTIMIZED: Added gaps parameter to avoid repainting on historical data
emaMtf = request.security(syminfo.tickerid, mtfTimeframe, emaSlow , lookahead = barmerge.lookahead_off)
bool mtfOkForBuy_ori = close > emaMtf
bool mtfOkForSell_ori = close < emaMtf
bool emaOkForBuy = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForBuy_ori : emaCrossOkForBuy)
bool emaOkForSell = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForSell_ori : emaCrossOkForSell)
// --- FILTER MOMENTUM ---
rsiFilter = ta.rsi(src, rsiLen_actual)
bool rsiOkForBuy = not _useRsiFilter or rsiFilter > rsiBuyLevel
bool rsiOkForSell = not _useRsiFilter or rsiFilter < rsiSellLevel
// --- FILTER CANDLE & VOLUME ---
bool bullishEngulfing = (close > open and close < open and close > open and open < close )
bool bearishEngulfing = (close < open and close > open and close < open and open > close )
bool candleOkForBuy = not _useCandleFilter or bullishEngulfing
bool candleOkForSell = not _useCandleFilter or bearishEngulfing
avgVolume = ta.sma(volume, volumeLen)
bool volumeOkForBuy = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
bool volumeOkForSell = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
// --- FILTER SNR ---
pivotHigh = ta.pivothigh(high, snrLookback, snrLookback)
pivotLow = ta.pivotlow(low, snrLookback, snrLookback)
float nearestResistance = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float nearestSupport = ta.valuewhen(not na(pivotLow), pivotLow, 0)
float snrDistance = xATR * snrDistanceFactor
bool nearResistance = math.abs(high - nearestResistance) < snrDistance and high > nearestResistance
bool nearSupport = math.abs(low - nearestSupport) < snrDistance and low < nearestSupport
bool snrOkForBuy = not _useSnrFilter or not nearResistance
bool snrOkForSell = not _useSnrFilter or not nearSupport
// --- FILTER ADX ---
= ta.dmi(adxLen_actual, adxLen_actual)
bool adxMarketOk = not _useAdxFilter or adxValue > adxMinLevel
bool adxDirectionOkForBuy = adxMarketOk and diPlus > diMinus
bool adxDirectionOkForSell = adxMarketOk and diMinus > diPlus
bool adxOkForBuy = not _useAdxFilter or adxDirectionOkForBuy
bool adxOkForSell = not _useAdxFilter or adxDirectionOkForSell
// ==============================================
// --- LOGIKA UPGRADE 1 ---
// ==============================================
float prevMidPoint = (high + low ) / 2
bool confirmOkForBuy = not useConfirmFilter or (close > prevMidPoint)
bool confirmOkForSell = not useConfirmFilter or (close < prevMidPoint)
// ==============================================
// --- LOGIKA CANDLE ---
// ==============================================
bool isBullishEngulfing_m = close > open and close < open and close >= open and open <= close
bool isBearishEngulfing_m = close < open and close > open and close <= open and open >= close
bool isHammer_m = (high - low) > 3 * math.abs(open - close) and ((close - low) / (0.001 + high - low)) > 0.6
bool isInvertedHammer_m = (high - low) > 3 * math.abs(open - close) and ((high - close) / (0.001 + high - low)) > 0.6
// ==============================================
// --- FILTER AKHIR (TANPA GHOST) ---
// ==============================================
bool filterBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and candleOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterSell = adxOkForSell and emaOkForSell and rsiOkForSell and candleOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
// ==============================================
// --- LOGIKA TRAILING STOP (CORE) ---
// ==============================================
var float xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
// --- KONDISI CROSS MENTAH (REALTIME) ---
bool crossUp_Raw = src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0)
bool crossDown_Raw = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0)
// ==============================================
// --- LOGIKA SINYAL (ANTI-KEDIP IMPLEMENTATION) ---
// ==============================================
// Variabel Posisi (State)
var int pos = 0
var float entryPrice = na
var float entryNloss = na
bool buySignal = false
bool sellSignal = false
// >> JANTUNG ANTI-KEDIP <<
if useConfirmedBar
// Cek Candle Kemarin . Jika kemarin valid, sinyal muncul SEKARANG (permanen).
bool crossUp_Prev = close < nz(xATRTrailingStop , 0) and close > nz(xATRTrailingStop , 0)
bool crossDown_Prev = close > nz(xATRTrailingStop , 0) and close < nz(xATRTrailingStop , 0)
// Gunakan filter dari bar sebelumnya agar konsisten
buySignal := crossUp_Prev and filterBuy
sellSignal := crossDown_Prev and filterSell
else
// Mode realtime (Risiko kedap-kedip)
buySignal := crossUp_Raw and filterBuy
sellSignal := crossDown_Raw and filterSell
// --- EKSEKUSI POSISI ---
// Cek Exit
bool closePositionBySL = (nz(pos ) == 1 and src < xATRTrailingStop) or (nz(pos ) == -1 and src > xATRTrailingStop)
bool reversalExitBuy = nz(pos ) == 1 and isBearishEngulfing_m
bool reversalExitSell = nz(pos ) == -1 and isBullishEngulfing_m
bool reversalCandleExit = useReversalExit and (reversalExitBuy or reversalExitSell)
bool exitSignal = closePositionBySL or reversalCandleExit
int newPos = nz(pos )
if buySignal
newPos := 1
else if sellSignal
newPos := -1
else if exitSignal
newPos := 0
pos := newPos
bool posOpen = pos != 0
// Update Entry Price
if buySignal or sellSignal
if useConfirmedBar
entryPrice := open
entryNloss := nLoss
else
entryPrice := src
entryNloss := nLoss
else if pos == 0
entryPrice := na
entryNloss := na
// --- LOGIKA ADD BUY / ADD SELL (SMART SNIPER V3.1) ---
bool validPullbackBuy = (close > open) and (close < open )
bool validPullbackSell = (close < open) and (close > open )
bool rsiSafeForAddBuy = rsiFilter < 75
bool rsiSafeForAddSell = rsiFilter > 25
bool filterAddBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterAddSell = adxOkForSell and emaOkForSell and rsiOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
bool addBuySignal = showReEntry and (pos == 1) and validPullbackBuy and filterAddBuy and rsiSafeForAddBuy and not buySignal
bool addSellSignal = showReEntry and (pos == -1) and validPullbackSell and filterAddSell and rsiSafeForAddSell and not sellSignal
// Auto Breakeven
float currentStopLoss = xATRTrailingStop
if posOpen and useAutoBreakeven and not na(entryPrice)
float profitRNeeded = breakevenFactor * entryNloss
float currentProfit = pos == 1 ? (src - entryPrice) : (entryPrice - src)
if currentProfit >= profitRNeeded
float breakevenLevel = entryPrice
if pos == 1
if breakevenLevel > currentStopLoss
currentStopLoss := breakevenLevel
else // pos == -1
if breakevenLevel < currentStopLoss
currentStopLoss := breakevenLevel
xATRTrailingStopAdj = posOpen ? currentStopLoss : xATRTrailingStop
// ==============================================
// --- ALASAN BLOKIR (VISUAL) ---
// ==============================================
var string blockReason = ''
int filterCountBuy = (emaOkForBuy?1:0)+(rsiOkForBuy?1:0)+(candleOkForBuy?1:0)+(volumeOkForBuy?1:0)+(adxOkForBuy?1:0)+(snrOkForBuy?1:0)+(confirmOkForBuy?1:0)
int filterCountSell = (emaOkForSell?1:0)+(rsiOkForSell?1:0)+(candleOkForSell?1:0)+(volumeOkForSell?1:0)+(adxOkForSell?1:0)+(snrOkForSell?1:0)+(confirmOkForSell?1:0)
if crossUp_Raw and not filterBuy
blockReason := '❌ Buy Blocked (' + str.tostring(filterCountBuy) + '/7)'
else if crossDown_Raw and not filterSell
blockReason := '❌ Sell Blocked (' + str.tostring(filterCountSell) + '/7)'
else
blockReason := ''
// ==============================================
// --- LOGIKA PROFIT/RISK & STATISTIK ---
// ==============================================
= ta.bb(src, bbLen, bbStdDev)
float distFromEntry = posOpen ? (pos == 1 ? src - nz(entryPrice) : nz(entryPrice) - src) : 0.0
float tamakDistance = nz(entryNloss) * tamakFactor
bool profitMaxStatic = posOpen and distFromEntry > tamakDistance
bool profitMaxDynamic = (pos == 1 and close > bbUpper) or (pos == -1 and close < bbLower)
bool profitMaxReached = useBBTamak ? profitMaxDynamic : profitMaxStatic
float profitNeededForTP = breakevenFactor * entryNloss
bool rsiReversal = (pos == 1 and rsiFilter > rsiReversalLevel) or (pos == -1 and rsiFilter < (100 - rsiReversalLevel))
bool reversalRiskDetected = posOpen and distFromEntry > profitNeededForTP and rsiReversal
// LOGIKA STATISTIK W/L
bool tradeEnded = (pos != pos ) and (pos != 0)
var int tradeCount_wins = 50
var int tradeCount_losses = 0
if tradeEnded
if pos == 1
if close > entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
else if pos == -1
if close < entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
// ==============================================
// --- VISUALISASI UTAMA (CLEAN) ---
// ==============================================
plotshape(buySignal, title='Buy Entry', text='Buy', style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white, size=size.tiny)
plotshape(sellSignal, title='Sell Entry', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.tiny)
plotshape(addBuySignal, title='Add Buy', text='Add', style=shape.triangleup, location=location.belowbar, color=color.blue, textcolor=color.blue, size=size.tiny)
plotshape(addSellSignal, title='Add Sell', text='Add', style=shape.triangledown, location=location.abovebar, color=color.fuchsia, textcolor=color.fuchsia, size=size.tiny)
plotshape(reversalCandleExit, title='Forced Exit', text='Exit', style=shape.labeldown, location=location.abovebar, color=color.gray, textcolor=color.white, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "BUY", title="Buy (Meter)", style=shape.triangleup, color=color.new(color.lime, 0), location=location.belowbar, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "SELL", title="Sell (Meter)", style=shape.triangledown, color=color.new(color.red, 0), location=location.abovebar, size=size.tiny)
var int limitBars = 300
last_record_index = bar_index
bool isRecentBar = bar_index > last_record_index - limitBars
pBuyZone = plot(pos == 1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
pSellZone = plot(pos == -1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
bool shouldFill = pos != 0 and isRecentBar and not reversalCandleExit
fillColor = pos == 1 ? color.new(color.green, 85) : pos == -1 ? color.new(color.red, 85) : na
fill(pBuyZone, pSellZone, color = shouldFill ? fillColor : na)
var line snr_res_line = na
var line snr_sup_line = na
if not na(pivotHigh)
line.delete(snr_res_line)
snr_res_line := line.new(bar_index, pivotHigh, bar_index + 1, pivotHigh, xloc.bar_index, extend.right, color.red, line.style_solid, 2)
if not na(pivotLow)
line.delete(snr_sup_line)
snr_sup_line := line.new(bar_index, pivotLow, bar_index + 1, pivotLow, xloc.bar_index, extend.right, color.green, line.style_solid, 2)
plot(useBBTamak ? bbUpper : na, title="BB Upper (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
plot(useBBTamak ? bbLower : na, title="BB Lower (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
float emaAggressiveFast = ta.ema(src, emaAggressiveFastLen)
float emaAggressiveSlow = ta.ema(src, emaAggressiveSlowLen)
plot(showAggressiveEMA ? emaAggressiveFast : na, title="EMA Agresif Cepat", color=color.new(#1ff118, 44), style=plot.style_cross, linewidth=1)
plot(showAggressiveEMA ? emaAggressiveSlow : na, title="EMA Agresif Lambat", color=color.new(#f8241d, 46), style=plot.style_cross, linewidth=1)
// ==============================================
// --- DASHBOARD PRO & STATUS (REALITY ADVISOR COMPACT) ---
// ==============================================
string statusText = ''
color statusColor = color.gray
float distFromStop = pos == 1 ? src - xATRTrailingStopAdj : pos == -1 ? xATRTrailingStopAdj - src : 0
bool waspada = pos != 0 and not buySignal and not sellSignal and distFromStop < waspadaFactor * entryNloss
int rand = bar_index % 5
var string advisorMsg = "..."
if buySignal
statusText := '🚀 NAIK! Entry Baru'
statusColor := color.green
if rand == 0
advisorMsg := "Gaspol! 🚀 Jangan keasyikan tambah SL+ sayang."
else if rand == 1
advisorMsg := "OTW Sultan! 🤑 Full senyum maszeh!"
else if rand == 2
advisorMsg := "Ijo royo-royo! 🌿 Mata jadi seger."
else if rand == 3
advisorMsg := "Sikat Pak Haji! 👳 Rejeki anak soleh."
else
advisorMsg := "Lilin hijau! Serok sekarang! 💰"
else if sellSignal
statusText := '📉 TURUN! Entry Baru'
statusColor := color.red
if rand == 0
advisorMsg := "Longsor! 📉 Siapkan ember."
else if rand == 1
advisorMsg := "Merah merona! 🩸 Dompet aman kan?"
else if rand == 2
advisorMsg := "Terjun bebas! 🪂 waspada REM."
else if rand == 3
advisorMsg := "Longsor! 📉 jangan naik dulu."
else
advisorMsg := "Short selling! Cuan tipis sikat! 💸"
else if addBuySignal
statusText := '🚀 GAS LAGI (Add)!'
statusColor := color.blue
if rand == 0
advisorMsg := "Tambah muatan! 😎 Biar bandar nangis."
else
advisorMsg := "Mumpung hijau! 🛒 Sikat lagi bosqu!"
else if addSellSignal
statusText := '📉 GAS LAGI (Add)!'
statusColor := color.fuchsia
if rand == 0
advisorMsg := "Tambah Sell! 🔥 Biar makin perih."
else
advisorMsg := "Tekan bawah! 😤 Jangan kasih napas."
else if reversalCandleExit
statusText := '⛔ EXIT! Pembalikan'
statusColor := color.orange
advisorMsg := "Kabur! 🏃💨 Candle mencurigakan."
else if reversalRiskDetected
statusText := '⚠️ TP NOW!'
statusColor := color.yellow
advisorMsg := "Amankan profit! 🤡 Jangan serakah."
else if profitMaxReached
statusText := '🤑 CUAN BUNGKUS!'
statusColor := color.aqua
if rand == 0
advisorMsg := "Cuan bungkus! 🍜 Traktir seblak dong."
else if rand == 1
advisorMsg := "Udah kaya? 💅 Tarik buat skincare!"
else
advisorMsg := "Alhamdulillah! 🎁 Rejeki jangan ditolak."
else if waspada
statusText := '💔 HATI-HATI!'
statusColor := color.orange
if rand == 0
advisorMsg := "Dia toxic... 🚩 Hati-hati SL."
else
advisorMsg := "Awas MC! 💀 pasang SL+ sayang."
else if pos == 1
statusText := '🧘 TAHAN Buy...'
statusColor := color.green
if rand == 0
advisorMsg := "Sabar sayang... 🧘♀️ Disayang Tuhan."
else if rand == 1
advisorMsg := "Biarkan lari! 🏃♂️ Profit is running."
else
advisorMsg := "Hold terus! 🚀 Sampai ke bulan!"
else if pos == -1
statusText := '🍿 TAHAN Sell...'
statusColor := color.red
if rand == 0
advisorMsg := "Nonton aja... 🍿 Sambil ngemil."
else
advisorMsg := "Jatuh kebawah sakit? 😂 disini malah Cuan."
else if blockReason != ''
statusText := "DIBLOKIR"
statusColor := color.gray
advisorMsg := "Sinyal busuk! ⛔ Jangan masuk."
else
statusText := '... '
statusColor := color.gray
if rand == 0
advisorMsg := "Market galau... 💤 Mending turu."
else if rand == 1
advisorMsg := "Datar banget... 😑 Kek jalan tol."
else if rand == 2
advisorMsg := "Jangan maksa! ☕ Ngopi dulu."
else
advisorMsg := "Sabar... 🕰️ Menunggu itu berat."
if adxValue > adxMinLevel and diPlus > diMinus
marketModeText := "📈 Tren Naik Kuat"
marketModeColor := color.new(color.green, 0)
else if adxValue > adxMinLevel and diMinus > diPlus
marketModeText := "📉 Tren Turun Kuat"
marketModeColor := color.new(color.red, 0)
else
marketModeText := "💤 Sideways / Chop"
marketModeColor := color.new(color.gray, 0)
f_fillCell(tbl, col, row, cellText, color) =>
table.cell(tbl, col, row, cellText, text_color=color, text_size=size.small)
f_drawDashboard() =>
f_fillCell(dashboardPanel, 0, 0, "Gaya:", color.gray)
f_fillCell(dashboardPanel, 1, 0, tradingStyle, color.white)
f_fillCell(dashboardPanel, 0, 1, "Status:", color.gray)
f_fillCell(dashboardPanel, 1, 1, statusText, statusColor)
bool dashboardContextIsBuy = pos == 1 or (pos == 0 and close > open)
string emaStatus = (dashboardContextIsBuy ? emaOkForBuy : emaOkForSell) or not _useEmaFilter ? "✅" : "❌"
string rsiStatus = (dashboardContextIsBuy ? rsiOkForBuy : rsiOkForSell) or not _useRsiFilter ? "✅" : "❌"
string adxStatus = (dashboardContextIsBuy ? adxOkForBuy : adxOkForSell) or not _useAdxFilter ? "✅" : "❌"
string snrStatus = (dashboardContextIsBuy ? snrOkForBuy : snrOkForSell) or not _useSnrFilter ? "✅" : "❌"
string confirmStatus = (dashboardContextIsBuy ? confirmOkForBuy : confirmOkForSell) or not useConfirmFilter ? "✅" : "❌"
string filterStr1 = "EMA" + emaStatus + " RSI" + rsiStatus
string filterStr2 = "ADX" + adxStatus + " SNR" + snrStatus + (useConfirmFilter ? " 1-Bar" + confirmStatus : "")
string filterString = filterStr1 + " " + filterStr2
f_fillCell(dashboardPanel, 0, 2, "Filter:", color.gray)
f_fillCell(dashboardPanel, 1, 2, filterString, color.white)
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string meterString = (close > open ? "🟢 " : "🔴 ") + bars_m + " " + str.tostring(confidence_m, "#") + "%"
f_fillCell(dashboardPanel, 0, 3, "Meter:", color.gray)
f_fillCell(dashboardPanel, 1, 3, meterString, (close > open ? color.green : color.red))
int totalTrades = tradeCount_wins + tradeCount_losses
f_fillCell(dashboardPanel, 0, 4, "Total Sinyal:", color.gray)
f_fillCell(dashboardPanel, 1, 4, str.tostring(totalTrades), color.white)
f_fillCell(dashboardPanel, 0, 5, "W / L:", color.gray)
f_fillCell(dashboardPanel, 1, 5, str.tostring(tradeCount_wins) + " / " + str.tostring(tradeCount_losses), color.white)
string winRateString = "N/A"
color winRateColor = color.gray
if totalTrades > 0
winRateString := str.tostring(tradeCount_wins / totalTrades * 100, '0.0') + "%"
winRateColor := tradeCount_wins > tradeCount_losses ? color.green : (tradeCount_losses > tradeCount_wins ? color.red : color.gray)
f_fillCell(dashboardPanel, 0, 6, "Win Rate:", color.gray)
f_fillCell(dashboardPanel, 1, 6, winRateString, winRateColor)
f_fillCell(dashboardPanel, 0, 7, "Pasar:", color.gray)
f_fillCell(dashboardPanel, 1, 7, marketModeText, marketModeColor)
table.merge_cells(dashboardPanel, 0, 8, 1, 8)
table.cell(dashboardPanel, 0, 8, advisorMsg, text_color=color.yellow, text_size=size.small, bgcolor=color.new(color.black, 50))
table.merge_cells(dashboardPanel, 0, 9, 1, 9)
table.cell(dashboardPanel, 0, 9, "HADYAN PREMIUM INDI 083174747475", text_color=color.new(#969087, 66), text_size=size.tiny)
if barstate.islast and showDashboard
f_drawDashboard()
else if barstate.islast
table.clear(dashboardPanel, 0, 0, 1, 9)
// ==============================================
// --- FLOATING BUBBLE LABEL (FIXED) ---
// ==============================================
var label advisorLabel = na
if barstate.islast
label.delete(advisorLabel)
if showAdvisorBubble
// Tentukan Warna Gelembung biar Cantik
color bubbleColor = color.new(color.gray, 20)
if buySignal or addBuySignal or pos == 1
bubbleColor := color.new(color.green, 20)
else if sellSignal or addSellSignal or pos == -1
bubbleColor := color.new(color.red, 20)
else if waspada or reversalCandleExit
bubbleColor := color.new(color.orange, 20)
// OPTIMIZED: Geser sedikit ke kanan (+2) agar tidak menutupi candle terakhir
advisorLabel := label.new(bar_index + 2, close, text=advisorMsg, color=bubbleColor, textcolor=color.white, style=label.style_label_left, yloc=yloc.price)
// ==============================================
// --- LOGIKA CANDLE METER PANEL ---
// ==============================================
if (showCandlePanel or showCandleArrows) and not showDashboard
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
string patternName_m = ""
string baseDir_m = close > open ? "BUY" : "SELL"
if isBullishEngulfing_m
patternName_m := "Bullish Engulfing"
baseDir_m := "BUY"
else if isBearishEngulfing_m
patternName_m := "Bearish Engulfing"
baseDir_m := "SELL"
else if isHammer_m
patternName_m := "Hammer"
baseDir_m := "BUY"
else if isInvertedHammer_m
patternName_m := "Inverted Hammer"
baseDir_m := "SELL"
else
patternName_m := "Normal Candle"
string trendConfirm_m = close > close and close > close ? "BUY" : close < close and close < close ? "SELL" : baseDir_m
finalDir_m := baseDir_m == trendConfirm_m ? baseDir_m : baseDir_m
if showCandlePanel
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string dirText_m = finalDir_m == "BUY" ? "🟢 BUY" : "🔴 SELL"
string confText_m = str.tostring(confidence_m, "#") + "% " + bars_m
table.cell(infoPanel_m, 0, 0, "Pattern", text_color=color.yellow)
table.cell(infoPanel_m, 1, 0, "Direction", text_color=color.yellow)
table.cell(infoPanel_m, 2, 0, "Confidence", text_color=color.yellow)
table.cell(infoPanel_m, 0, 1, patternName_m, text_color=color.white)
table.cell(infoPanel_m, 1, 1, dirText_m, text_color=color.white)
table.cell(infoPanel_m, 2, 1, confText_m, text_color=color.white)
else
table.clear(infoPanel_m, 0, 0, 2, 1)
else if not showDashboard
table.clear(infoPanel_m, 0, 0, 2, 1)
// ==============================================
// --- ALERT UPDATED (SINGLE ALERT SUPPORT) ---
// ==============================================
string alertMsg_all = ""
if buySignal
alertMsg_all := "🚀 BUY NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if sellSignal
alertMsg_all := "📉 SELL NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if addBuySignal
alertMsg_all := "➕ ADD BUY (Re-Entry) @ " + str.tostring(close)
else if addSellSignal
alertMsg_all := "➕ ADD SELL (Re-Entry) @ " + str.tostring(close)
else if reversalCandleExit
alertMsg_all := "⛔ EXIT NOW! Reversal Detected @ " + str.tostring(close)
else if profitMaxReached
alertMsg_all := "💰 TAKE PROFIT! Target Tercapai @ " + str.tostring(close)
else if reversalRiskDetected
alertMsg_all := "⚠️ WARNING REVERSAL! RSI Extreme @ " + str.tostring(close)
// Pemicu Alarm Utama (Hanya aktif jika ada pesan, cukup pasang 1 alarm "Any function call")
if alertMsg_all != ""
alert(alertMsg_all, alert.freq_once_per_bar_close)
// Backup: Manual Alerts (Jika user Premium mau pasang satu-satu)
alertcondition(buySignal, title=' Buy Signal', message='🚀 BUY NEW!')
alertcondition(sellSignal, title=' Sell Signal', message='📉 SELL NEW!')
alertcondition(addBuySignal, title=' Add Buy', message='🚀 ADD BUY')
alertcondition(addSellSignal, title=' Add Sell', message='📉 ADD SELL')
alertcondition(waspada, title=' Waspada', message='💔 WASPADA')
// ==============================================
// --- TP/SL MODE SWING (FIXED & OPTIMIZED) ---
// ==============================================
var line sl_line = na
var line tp1_line = na
var line tp2_line = na
var line tp3_line = na
var label sl_label = na
var label tp1_label = na
var label tp2_label = na
var label tp3_label = na
if tradingStyle == 'Swing Santai'
if buySignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice - entryNloss
float tp1 = entryPrice + entryNloss
float tp2 = entryPrice + (2*entryNloss)
float tp3 = entryPrice + (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if sellSignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice + entryNloss
float tp1 = entryPrice - entryNloss
float tp2 = entryPrice - (2*entryNloss)
float tp3 = entryPrice - (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if pos != 0 and not na(sl_line)
// Update existing lines (Lightweight)
line.set_x2(sl_line, bar_index + 10)
line.set_x2(tp1_line, bar_index + 10)
line.set_x2(tp2_line, bar_index + 10)
line.set_x2(tp3_line, bar_index + 10)
label.set_x(sl_label, bar_index + 10)
label.set_x(tp1_label, bar_index + 10)
label.set_x(tp2_label, bar_index + 10)
label.set_x(tp3_label, bar_index + 10)
else if pos == 0
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
else
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
// ==============================================
// --- UPGRADE BARU: PIVOT POINTS (FIXED: EXTEND RIGHT) ---
// ==============================================
// Dapatkan Daily High, Low, Close (FIX "D")
p_d_h = request.security(syminfo.tickerid, "D", high , lookahead=barmerge.lookahead_on)
p_d_l = request.security(syminfo.tickerid, "D", low , lookahead=barmerge.lookahead_on)
p_d_c = request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_on)
// Perhitungan Pivot Klasik
pivot_d = (p_d_h + p_d_l + p_d_c) / 3
r1_d = 2 * pivot_d - p_d_l
s1_d = 2 * pivot_d - p_d_h
r2_d = pivot_d + (p_d_h - p_d_l)
s2_d = pivot_d - (p_d_h - p_d_l)
// Visualisasi Pivot
var line p_line = na
var line r1_line = na
var line s1_line = na
var line r2_line = na
var line s2_line = na
var label p_label = na
var label r1_label = na
var label s1_label = na
var label r2_label = na
var label s2_label = na
// Fungsi untuk menghapus label/line
f_delete_pivot_objects() =>
line.delete(p_line)
line.delete(r1_line)
line.delete(s1_line)
line.delete(r2_line)
line.delete(s2_line)
label.delete(p_label)
label.delete(r1_label)
label.delete(s1_label)
label.delete(r2_label)
label.delete(s2_label)
if showPivotPoints
// Hapus yang lama agar tidak numpuk (Redraw Logic)
f_delete_pivot_objects()
// Logic: EXTEND RIGHT (Memanjang)
// Kita gunakan extend.right agar garisnya tidak pernah putus ke kanan
// Pivot (P)
p_line := line.new(bar_index, pivot_d, bar_index + 1, pivot_d, xloc.bar_index, extend.right, pivotColor, line.style_solid, 2)
p_label := label.new(bar_index + 10, pivot_d, "P Daily: " + str.tostring(pivot_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(pivotColor, 20), textcolor=color.white, style=label.style_label_left, size=size.small)
// Resistance
r1_line := line.new(bar_index, r1_d, bar_index + 1, r1_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r1_label := label.new(bar_index + 10, r1_d, "R1: " + str.tostring(r1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
r2_line := line.new(bar_index, r2_d, bar_index + 1, r2_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r2_label := label.new(bar_index + 10, r2_d, "R2: " + str.tostring(r2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
// Support
s1_line := line.new(bar_index, s1_d, bar_index + 1, s1_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s1_label := label.new(bar_index + 10, s1_d, "S1: " + str.tostring(s1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
s2_line := line.new(bar_index, s2_d, bar_index + 1, s2_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s2_label := label.new(bar_index + 10, s2_d, "S2: " + str.tostring(s2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
else
f_delete_pivot_objects()
// ==============================================
// --- UPGRADE BARU: FIBONACCI RETRACEMENT (CLEAN NO STACK) ---
// ==============================================
var float fiboHigh = na
var float fiboLow = na
var int fiboStartBar = na
// Array untuk menyimpan objek Fibo
var line fiboLines = array.new(0)
var linefill fiboFills = array.new(0)
var label fiboLabels = array.new(0)
// Helper Function: Clean Up All Fibo Objects
f_cleanFibo() =>
if array.size(fiboLines) > 0
for i = 0 to array.size(fiboLines) - 1
line.delete(array.get(fiboLines, i))
array.clear(fiboLines)
if array.size(fiboFills) > 0
for i = 0 to array.size(fiboFills) - 1
linefill.delete(array.get(fiboFills, i))
array.clear(fiboFills)
if array.size(fiboLabels) > 0
for i = 0 to array.size(fiboLabels) - 1
label.delete(array.get(fiboLabels, i))
array.clear(fiboLabels)
// Calculate historical values globally
float lastHigh_scanned = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float lastLow_scanned = ta.valuewhen(not na(pivotLow), pivotLow, 0)
// Reset Fibo jika ada sinyal entry baru
if buySignal or sellSignal
f_cleanFibo() // Clean old ones first!
// Gunakan nilai yang sudah di-scan secara global
if not na(lastHigh_scanned) and not na(lastLow_scanned)
fiboLow := lastLow_scanned
fiboHigh := lastHigh_scanned
fiboStartBar := bar_index
// Levels
fiboLevels = array.new(0)
array.push(fiboLevels, 0.0)
array.push(fiboLevels, 0.236)
array.push(fiboLevels, 0.382)
array.push(fiboLevels, 0.5)
array.push(fiboLevels, 0.618)
array.push(fiboLevels, 1.0)
// Gambar Fibo (Hanya digambar ulang jika posisi valid dan belum ada)
// Kita gunakan trik: Gambar setiap bar, tapi HAPUS yang lama dulu.
// Ini mencegah stacking ribuan kotak.
if showFiboLevels and not na(fiboHigh) and not na(fiboLow)
f_cleanFibo() // CLEANUP WAJIB SEBELUM GAMBAR BARU
float fiboRange = fiboHigh - fiboLow
int f_start = bar_index + fiboXOffset
int f_end = bar_index + fiboXOffset + 15
var line lastLineObj = na
for i = 0 to array.size(fiboLevels) - 1
float level = array.get(fiboLevels, i)
float fiboPrice = fiboHigh - (fiboRange * level)
string levelText = str.tostring(math.round(level * 100), "0.0") + "%"
color levelColor = color.rgb(19, 56, 189)
if level == 0.618
levelColor := color.new(#FFD700, 30)
else if level == 0.5
levelColor := color.new(color.green, 30)
else
levelColor := color.new(#7925c9, 70)
string l_style = (level == 0.0 or level == 1.0) ? line.style_dashed : line.style_solid
int l_width = (level == 0.618 or level == 0.5) ? 2 : 1
// Draw & Push Line
line currentLineObj = line.new(f_start, fiboPrice, f_end, fiboPrice, xloc.bar_index, extend.none, levelColor, l_style, l_width)
array.push(fiboLines, currentLineObj)
// Fill Logic
color c_fill = switch level
0.236 => color.new(color.gray, 70) // Sangat transparan (95)
0.382 => color.new(color.blue, 70)
0.5 => color.new(color.green, 70)
0.618 => color.new(#FFD700, 70)
1.0 => color.new(color.red, 70)
=> na
if i > 0
linefill lf = linefill.new(lastLineObj, currentLineObj, c_fill)
array.push(fiboFills, lf)
lastLineObj := currentLineObj
// Draw & Push Label
label lb = label.new(f_end, fiboPrice, levelText, xloc.bar_index, yloc.price, color=color.new(levelColor, 100), textcolor=levelColor, style=label.style_label_left, size=size.small)
array.push(fiboLabels, lb)
// ==============================================
// --- UPGRADE BARU: STOCHASTIC FLOATING MINI CHART (REALTIME ANCHOR RIGHT PATCH) ---
// ==============================================
// 1. Calculations
stochK = ta.sma(ta.stoch(close, high, low, 14), 3)
stochD = ta.sma(stochK, 3)
// 2. Data Storage (Arrays for History)
var float stochK_hist = array.new_float(0)
var float stochD_hist = array.new_float(0)
// Update Arrays (REALTIME LOGIC)
if barstate.isnew
array.push(stochK_hist, nz(stochK, 50))
array.push(stochD_hist, nz(stochD, 50))
// Limit array size to chart width + 1
if array.size(stochK_hist) > (stochWidth + 1)
array.shift(stochK_hist)
array.shift(stochD_hist)
else
// UPDATE TICK-BY-TICK (Agar tidak delay)
if array.size(stochK_hist) > 0
array.set(stochK_hist, array.size(stochK_hist) - 1, nz(stochK, 50))
array.set(stochD_hist, array.size(stochD_hist) - 1, nz(stochD, 50))
// 3. Drawing Logic
var box stochBgBox = na
var box stochUpperFill = na
var box stochLowerFill = na
var line stochLines = array.new_line(0)
// Clear Function
f_cleanStochChart() =>
if not na(stochBgBox)
box.delete(stochBgBox)
if not na(stochUpperFill)
box.delete(stochUpperFill)
if not na(stochLowerFill)
box.delete(stochLowerFill)
if array.size(stochLines) > 0
for i = 0 to array.size(stochLines) - 1
line.delete(array.get(stochLines, i))
array.clear(stochLines)
// Global Helper to map 0-100 Stoch value to Y price coordinate
f_mapY(_val, _bottom, _height) =>
_bottom + (_val / 100 * _height)
if showStochChart and array.size(stochK_hist) > 2
f_cleanStochChart() // Redraw every tick
// Positioning (ANCHOR RIGHT LOGIC)
int offset_right = 5
int ch_right = bar_index + offset_right // Ujung kanan box
int ch_left = ch_right - stochWidth
// Vertical Scaling
float ch_height = ta.atr(14) * 4
float ch_bottom = close - (ch_height * 1.5)
float ch_top = ch_bottom + ch_height
// Draw Background
stochBgBox := box.new(ch_left, ch_top, ch_right, ch_bottom, xloc=xloc.bar_index, border_width=1, border_color=color.new(color.white, 80), bgcolor=color.new(color.black, 100))
// Draw Overbought Fill (80-100)
stochUpperFill := box.new(ch_left, f_mapY(70, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.red, 100))
// Draw Oversold Fill (0-20)
stochLowerFill := box.new(ch_left, f_mapY(10, ch_bottom, ch_height), ch_right, f_mapY(0, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.green, 100))
// Draw Reference Lines
line l80 = line.new(ch_left, f_mapY(80, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), color=color.new(color.red, 20), style=line.style_dotted)
line l20 = line.new(ch_left, f_mapY(20, ch_bottom, ch_height), ch_right, f_mapY(20, ch_bottom, ch_height), color=color.new(color.green, 20), style=line.style_dotted)
array.push(stochLines, l80)
array.push(stochLines, l20)
// Draw K and D Lines (ANCHOR TO REALTIME BAR INDEX)
// PATCH: Iterate relative to current bar_index to ensure 0 gap
int sz = array.size(stochK_hist)
for i = 0 to sz - 2
// Logika Mundur: Titik terakhir (sz-1) harus ada di bar_index saat ini
int idx_current = sz - 1 - i
int idx_prev = sz - 2 - i
if idx_prev >= 0
// X Coordinates (Relative to Realtime Bar)
int x2 = bar_index - i
int x1 = bar_index - (i + 1)
// K Line
float yK1 = f_mapY(array.get(stochK_hist, idx_prev), ch_bottom, ch_height)
float yK2 = f_mapY(array.get(stochK_hist, idx_current), ch_bottom, ch_height)
if not na(yK1) and not na(yK2)
line lK = line.new(x1, yK1, x2, yK2, color=color.new(#05492f, 0), width=1)
array.push(stochLines, lK)
// D Line
float yD1 = f_mapY(array.get(stochD_hist, idx_prev), ch_bottom, ch_height)
float yD2 = f_mapY(array.get(stochD_hist, idx_current), ch_bottom, ch_height)
if not na(yD1) and not na(yD2)
line lD = line.new(x1, yD1, x2, yD2, color=color.new(#810404, 0), width=1)
array.push(stochLines, lD)
// ==============================================
// --- VISUALISASI UPGRADE: SMART SUPPLY/DEMAND ZONES ---
// ==============================================
ph_zone = ta.pivothigh(high, zoneLookback, zoneLookback)
pl_zone = ta.pivotlow(low, zoneLookback, zoneLookback)
// FIX: Pindahkan ATR ke luar IF agar konsisten
float atrForZone = ta.atr(14)
var box supplyBoxes = array.new_box()
var box demandBoxes = array.new_box()
// Batasi jumlah zona agar chart tetap bersih
maxZones = 5
// Deteksi Zona Supply (Merah)
if not na(ph_zone) and showSmartZones
// Buat box baru dari titik pivot sampai ke masa depan sedikit
b_sup = box.new(bar_index , high , bar_index + 20, high - (atrForZone*0.5), bgcolor=color.new(color.red, 85), border_color=color.new(color.red, 50))
array.push(supplyBoxes, b_sup)
if array.size(supplyBoxes) > maxZones
box.delete(array.shift(supplyBoxes))
// Deteksi Zona Demand (Hijau)
if not na(pl_zone) and showSmartZones
b_dem = box.new(bar_index , low , bar_index + 20, low + (atrForZone*0.5), bgcolor=color.new(color.lime, 85), border_color=color.new(color.lime, 50))
array.push(demandBoxes, b_dem)
if array.size(demandBoxes) > maxZones
box.delete(array.shift(demandBoxes))
// Perpanjang Zona Secara Realtime
if array.size(supplyBoxes) > 0 and showSmartZones
for i = 0 to array.size(supplyBoxes) - 1
b = array.get(supplyBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
if array.size(demandBoxes) > 0 and showSmartZones
for i = 0 to array.size(demandBoxes) - 1
b = array.get(demandBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
// ====================================================================================================
// BAGIAN 2: FITUR TAMBAHAN (HSN GHOST CANDLES) - DI-INJECT DI SINI
// ====================================================================================================
// --- TIPE DATA KHUSUS (HSN) ---
type CandleHSN
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
box body
line wick_up
line wick_down
type ImbalanceHSN
box b
int idx
type CandleSettingsHSN
bool show
string htf
int max_display
type SettingsHSN
int max_sets
color bull_body
color bull_border
color bull_wick
color bear_body
color bear_border
color bear_wick
int offset
int buffer
int htf_buffer
int width
bool trace_show
string trace_anchor
bool label_show
color label_color
string label_size
bool htf_label_show
color htf_label_color
string htf_label_size
bool htf_timer_show
color htf_timer_color
string htf_timer_size
type CandleSetHSN
CandleHSN candles
ImbalanceHSN imbalances
CandleSettingsHSN settings
label tfName
label tfTimer
type HelperHSN
string name = "Helper"
// --- SETUP PENGATURAN HSN ---
SettingsHSN settings = SettingsHSN.new()
var CandleSettingsHSN SettingsHTF1 = CandleSettingsHSN.new()
var CandleSettingsHSN SettingsHTF2 = CandleSettingsHSN.new()
var CandleHSN candles_1 = array.new(0)
var CandleHSN candles_2 = array.new(0)
var CandleSetHSN htf1 = CandleSetHSN.new()
htf1.settings := SettingsHTF1
htf1.candles := candles_1
var CandleSetHSN htf2 = CandleSetHSN.new()
htf2.settings := SettingsHTF2
htf2.candles := candles_2
// --- INPUT KHUSUS HSN CANDLES (15 & 30 MENIT) ---
grp_hsn = "🔥 HSN HTF Candles (Upgrade)"
htf1.settings.show := input.bool(true, "Show HTF 1 (15 Menit)", group=grp_hsn, inline="h1")
htf_1 = input.timeframe("15", "", group=grp_hsn, inline="h1")
htf1.settings.htf := htf_1
htf1.settings.max_display := 4
htf2.settings.show := input.bool(true, "Show HTF 2 (30 Menit)", group=grp_hsn, inline="h2")
htf_2 = input.timeframe("30", "", group=grp_hsn, inline="h2")
htf2.settings.htf := htf_2
htf2.settings.max_display := 4
settings.max_sets := 2
settings.bull_body := color.new(color.green, 60)
settings.bear_body := color.new(color.red, 60)
settings.bull_border := color.new(color.green, 10)
settings.bear_border := color.new(color.red, 10)
settings.bull_wick := color.new(color.green, 10)
settings.bear_wick := color.new(color.red, 10)
// FIXED: Increased default offset from 10 to 25 to avoid overlap with Advisor Bubble
settings.offset := input.int(25, "Padding/Jarak Candle", group=grp_hsn)
settings.buffer := 1
settings.htf_buffer := 5
settings.width := input.int(1, "Lebar Candle", minval = 1, maxval = 4, group=grp_hsn)*2
settings.htf_label_show := true
settings.htf_label_color := color.gray
settings.htf_label_size := size.normal
// --- HELPER FUNCTIONS ---
HelperHSN helper = HelperHSN.new()
color color_transparent = #ffffff00
method ValidTimeframe(HelperHSN helper, string HTF) =>
helper.name := HTF
if timeframe.in_seconds(HTF) >= timeframe.in_seconds("D") and timeframe.in_seconds(HTF) > timeframe.in_seconds()
true
else
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(HTF)
n3 = n1 % n2
(n1 < n2 and math.round(n2/n1) == n2/n1)
method HTFName(HelperHSN helper, string HTF) =>
helper.name := "HTFName"
formatted = HTF
seconds = timeframe.in_seconds(HTF)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted
method HTFEnabled(HelperHSN helper) =>
helper.name := "HTFEnabled"
int enabled =0
enabled += htf1.settings.show ? 1 : 0
enabled += htf2.settings.show ? 1 : 0
int last = math.min(enabled, settings.max_sets)
last
method CandleSetHigh(HelperHSN helper, CandleHSN candles, float h) =>
helper.name := "CandlesSetHigh"
float _h = h
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > _h
_h := cItem.h
_h
method CandlesHigh(HelperHSN helper, CandleHSN candles) =>
helper.name := "CandlesHigh"
h = 0.0
int cnt = 0
int last = helper.HTFEnabled()
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
h := helper.CandleSetHigh(htf1.candles, h)
cnt += 1
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt < last
h := helper.CandleSetHigh(htf2.candles, h)
cnt +=1
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > h
h := cItem.h
h
method Reorder(CandleSetHSN candleSet, int offset) =>
size = candleSet.candles.size()
if size > 0
for i = size-1 to 0
CandleHSN candle = candleSet.candles.get(i)
t_buffer = offset + ((settings.width+settings.buffer)*(size-i-1))
box.set_left(candle.body, bar_index + t_buffer)
box.set_right(candle.body, bar_index + settings.width + t_buffer)
line.set_x1(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x1(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
top = helper.CandlesHigh(candleSet.candles)
left = bar_index + offset + ((settings.width+settings.buffer)*(size-1))/2
if settings.htf_label_show
var label l = candleSet.tfName
string lbl = helper.HTFName(candleSet.settings.htf)
if not na(l)
label.set_xy(l, left, top)
else
l := label.new(left, top, lbl, color=color_transparent, textcolor = settings.htf_label_color, style=label.style_label_down, size = settings.htf_label_size)
candleSet
method Monitor(CandleSetHSN candleSet) =>
HTFBarTime = time(candleSet.settings.htf)
isNewHTFCandle = ta.change(HTFBarTime)
if isNewHTFCandle
CandleHSN candle = CandleHSN.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.o_idx := bar_index
candle.c_idx := bar_index
candle.h_idx := bar_index
candle.l_idx := bar_index
bull = candle.c > candle.o
candle.body := box.new(bar_index, math.max(candle.o, candle.c), bar_index+2, math.min(candle.o, candle.c), bull ? settings.bull_border : settings.bear_border, 1, bgcolor = bull ? settings.bull_body : settings.bear_body)
candle.wick_up := line.new(bar_index+1, candle.h, bar_index, math.max(candle.o, candle.c), color=bull ? settings.bull_wick : settings.bear_wick)
candle.wick_down := line.new(bar_index+1, math.min(candle.o, candle.c), bar_index, candle.l, color=bull ? settings.bull_wick : settings.bear_wick)
candleSet.candles.unshift(candle)
if candleSet.candles.size() > candleSet.settings.max_display
CandleHSN delCandle = array.pop(candleSet.candles)
box.delete(delCandle.body)
line.delete(delCandle.wick_up)
line.delete(delCandle.wick_down)
candleSet
method Update(CandleSetHSN candleSet, int offset) =>
if candleSet.candles.size() > 0
CandleHSN candle = candleSet.candles.first()
candle.h_idx := high > candle.h ? bar_index : candle.h_idx
candle.h := high > candle.h ? high : candle.h
candle.l_idx := low < candle.l ? bar_index : candle.l_idx
candle.l := low < candle.l ? low : candle.l
candle.c := close
candle.c_idx := bar_index
bull = candle.c > candle.o
box.set_top(candle.body, bull ? candle.c : candle.o)
box.set_bottom(candle.body, bull ? candle.o : candle.c)
box.set_bgcolor(candle.body, bull ? settings.bull_body : settings.bear_body)
box.set_border_color(candle.body, bull ? settings.bull_border : settings.bear_border)
line.set_color(candle.wick_up, bull ? settings.bull_wick : settings.bear_wick)
line.set_color(candle.wick_down, bull ? settings.bull_wick : settings.bear_wick)
line.set_y1(candle.wick_up, candle.h)
line.set_y2(candle.wick_up, math.max(candle.o, candle.c))
line.set_y1(candle.wick_down, candle.l)
line.set_y2(candle.wick_down, math.min(candle.o, candle.c))
if barstate.isrealtime or barstate.islast
candleSet.Reorder(offset)
candleSet
// --- EKSEKUSI HSN LOGIC ---
int cnt_hsn = 0
int last_hsn = helper.HTFEnabled()
int offset_hsn = settings.offset
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
htf1.Monitor().Update(offset_hsn)
cnt_hsn +=1
offset_hsn += cnt_hsn > 0 ? (htf1.candles.size() * settings.width) + (htf1.candles.size() > 0 ? htf1.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt_hsn < last_hsn
htf2.Monitor().Update(offset_hsn)
cnt_hsn+=1
offset_hsn += cnt_hsn > 0 ? (htf2.candles.size() * settings.width) + (htf2.candles.size() > 0 ? htf2.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
EMA Scalping RR 1:2//@version=5
indicator("EMA RR 1:2 Scalping (24H + Fixed SL)", overlay=true, max_labels_count=200, max_lines_count=200)
// ===== INPUT =====
fastLen = input.int(9, "Fast EMA")
slowLen = input.int(21, "Slow EMA")
rr = input.float(2.0, "Risk Reward", step=0.1)
atrLen = input.int(14, "ATR Length")
slATR = input.float(1.0, "SL = ATR x", step=0.1)
adxLen = input.int(14, "ADX Length")
minADX = input.int(20, "Min ADX")
bodyATR = input.float(0.5, "Big Candle vs ATR", step=0.1)
// ===== EMA =====
emaFast = ta.ema(close, fastLen)
emaSlow = ta.ema(close, slowLen)
plot(emaFast, color=color.orange, linewidth=2)
plot(emaSlow, color=color.blue, linewidth=2)
// ===== ATR & CANDLE =====
atrVal = ta.atr(atrLen)
bigBody = math.abs(close - open) >= atrVal * bodyATR
// ===== MANUAL ADX =====
upMove = high - high
downMove = low - low
plusDM = (upMove > downMove and upMove > 0) ? upMove : 0
minusDM = (downMove > upMove and downMove > 0) ? downMove : 0
trur = ta.rma(ta.tr(true), adxLen)
plusDI = 100 * ta.rma(plusDM, adxLen) / trur
minusDI = 100 * ta.rma(minusDM, adxLen) / trur
dx = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
adx = ta.rma(dx, adxLen)
trendOK = adx >= minADX
// ===== SIGNAL =====
buySignal =
trendOK and bigBody and
emaFast > emaSlow and close > emaFast and close <= emaFast
sellSignal =
trendOK and bigBody and
emaFast < emaSlow and close < emaFast and close >= emaFast
// ===== BUY =====
if buySignal
entry = close
sl = entry - atrVal * slATR
tp = entry + (entry - sl) * rr
label.new(bar_index, low,
"BUY Entry: " + str.tostring(entry) +
" SL: " + str.tostring(sl) +
" TP: " + str.tostring(tp),
style=label.style_label_up,
color=color.green,
textcolor=color.white)
line.new(bar_index, entry, bar_index+12, entry)
line.new(bar_index, sl, bar_index+12, sl, color=color.red)
line.new(bar_index, tp, bar_index+12, tp, color=color.green)
// ===== SELL =====
if sellSignal
entry = close
sl = entry + atrVal * slATR
tp = entry - (sl - entry) * rr
label.new(bar_index, high,
"SELL Entry: " + str.tostring(entry) +
" SL: " + str.tostring(sl) +
" TP: " + str.tostring(tp),
style=label.style_label_down,
color=color.red,
textcolor=color.white)
line.new(bar_index, entry, bar_index+12, entry)
line.new(bar_index, sl, bar_index+12, sl, color=color.red)
line.new(bar_index, tp, bar_index+12, tp, color=color.green)
The Charlie Method - EnhancedThe Charlie Method is a precision-engineered 15-minute confirmation tool built for disciplined traders who wait for price to come to them.
It identifies only true bullish and bearish engulfing candles, visually marking them at the moment of confirmation and delivering immediate alerts.
No repainting. No noise. No distractions.
This method is best applied at key levels, liquidity zones, and session extremes, where confirmation matters most.
Trade less. Confirm more. Execute with intent.
Smart Signal Assistant (Kewme)Smart Signal Assistant (Kewme) – Professional Trading Suite
Overview The Smart Signal Assistant (Kewme) is a comprehensive, all-in-one trading toolkit designed to bring institutional-grade discipline and visual clarity to your trading. Unlike clutter-heavy indicators, this system focuses on precision and risk management. It combines a powerful trend-following engine with an automated trade manager that visualizes your risk and reward in real-time.
Key Features
1. 🛡️ Disciplined Trade Management (One Trade at a Time) Stop over-trading with the built-in "Focus Mode."
No Signal Spam: The system will never generate a new signal while a trade is currently running.
Active Management: A new signal is only generated after the current trade has either hit the Take Profit (TP) or the Stop Loss (SL). This enforces strict trading discipline.
2. 📦 Dynamic Risk/Reward Boxes Visualizing your trade has never been easier.
Instant Zones: Upon a signal, the script automatically draws a Green Profit Zone and a Red Loss Zone directly on the chart.
ATR-Based Precision: Stop Loss levels are calculated dynamically using Average True Range (ATR), ensuring your stops breathe with market volatility.
Auto-Cutoff: The boxes automatically stop drawing the moment price hits your TP or SL, keeping your chart clean and historical performance visible.
3. 🎯 Clear Exit Labels No more guessing. The script clearly marks the exact candle where your trade closed:
TP Hit 🎯: Appears when your target is reached.
SL Hit ❌: Appears if the market goes against you.
4. 🚀 Smart Trend Engine & Filters
Hybrid Modes: Choose between "Swing" (for reliable, long-term trends) or "Scalping" (for quick, short-term moves).
Trend-Range Classifier (TRC): An intelligent filter system that monitors ADX and market volatility. It automatically blocks signals during choppy, sideways markets to protect your capital.
5. 📊 Live Status Dashboard A sleek, on-chart dashboard provides real-time data at a glance:
Trade Status: Shows if a trade is "RUNNING" or "SEARCHING."
Market Bias: Bullish or Bearish.
Trend Strength: Indicates if the market is Strong or Sideways.
How to Use
Select Mode: Choose 'Swing' for higher timeframes or 'Scalping' for lower timeframes in settings.
Adjust Risk: Set your preferred Risk/Reward Ratio (e.g., 1:2) and SL Multiplier.
Follow the Boxes: Enter when the box appears, and exit exactly when the "TP Hit" or "SL Hit" label pops up.
Disclaimer: This tool is for educational and assistance purposes only. Always use proper risk management.
Al Sat Alpha Hunter System [MTF + Risk Manager]çok güzel yerlerden al sat komutu çıkıyor ve bunu size ücretsiz vermek istedim sizde faydalanın
Smart Buy/Sell Zones (Auto Timeframe)Brodrick Johnson Smart Zones.
Value zones for calculating price ceiling and floor.
XAUUSD Pro Strategy //@version=5
indicator("XAUUSD RR Buy Sell Indicator", overlay=true, max_labels_count=500, max_boxes_count=100)
// ===== INPUT =====
rr = input.float(2.0, "Risk Reward", step=0.1)
sl_pips = input.int(300, "Stop Loss (points)")
show_boxes = input.bool(true, "Show Entry SL TP Box")
// ===== EMA =====
ema9 = ta.ema(close, 9)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
plot(ema9, color=color.yellow)
plot(ema50, color=color.blue)
plot(ema200,color=color.red)
// ===== TREND =====
bull = ema50 > ema200
bear = ema50 < ema200
// ===== ENTRY CONDITIONS =====
buyCond = bull and close > ema9 and close < ema9
sellCond = bear and close < ema9 and close > ema9
// ===== PRICE CALC =====
buyEntry = close
buySL = buyEntry - sl_pips * syminfo.mintick
buyTP = buyEntry + (buyEntry - buySL) * rr
sellEntry = close
sellSL = sellEntry + sl_pips * syminfo.mintick
sellTP = sellEntry - (sellSL - sellEntry) * rr
// ===== DRAW =====
if buyCond
label.new(bar_index, low, "BUY", style=label.style_label_up, color=color.green, textcolor=color.white)
if show_boxes
box.new(bar_index, buyEntry, bar_index + 5, buySL, bgcolor=color.new(color.red,80))
box.new(bar_index, buyTP, bar_index + 5, buyEntry, bgcolor=color.new(color.green,80))
if sellCond
label.new(bar_index, high, "SELL", style=label.style_label_down, color=color.red, textcolor=color.white)
if show_boxes
box.new(bar_index, sellSL, bar_index + 5, sellEntry, bgcolor=color.new(color.red,80))
box.new(bar_index, sellEntry, bar_index + 5, sellTP, bgcolor=color.new(color.green,80))
SK INTRAY SETUPthis indicator help to trade in the primary trend direction with align and in direction of the trend
Market Structure- Zig Zag, BoS and Supply/Demand Zones LIMITLESS// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © The_Forex_Steward
//@version=6
indicator("Market Structure- Zig Zag, BoS and Supply/Demand Zones", overlay=true)
// === User Inputs ===
htf = input.timeframe("", title="Timeframe")
internalShiftMode = input.string("Engulfment", title="Calculate Zig-Zag By", options= )
x = input.int(1, minval=1, maxval= 3, title="# of Candles for Zones (1-3)")
showBearishOrderBlocks = input.bool(true, title="Show Supply Zones")
showBullishOrderBlocks = input.bool(true, title="Show Demand Zones")
orderBlockDuration = input.int(10, title="Zone Duration (bars)")
deleteMitigatedBoxes = input.bool(false, title="Delete Mitigated Zones")
deleteBrokenBoxes= input.bool(true, title = "Delete Broken Zones")
dimMitigatedBoxes = input.bool(true, title="Dim Mitigated Zones")
bearishBlockColor = input.color(color.rgb(255, 82, 82, 50), title="Supply Zone Fill")
bullishBlockColor = input.color(color.rgb(76, 175, 79, 50), title="Demand Zone Fill")
lighterBullishColor = color.new(bullishBlockColor, 85) // More transparent
lighterBearishColor = color.new(bearishBlockColor, 85)
zigzagLineColor = input.color(color.black, title="ZigZag Line Color")
zigzagLineWidth = input.int(2, title="Width of Lines", minval=1, maxval=10)
zigzagLineStyle = input.string("Solid", title="ZigZag Line Style", options= )
internalShiftColor = color.new(zigzagLineColor, 75) // More transparent
bosBullishLineColor = input.color(color.green, title="Bullish BOS Line Color")
bosBearishLineColor = input.color(color.red, title="Bearish BOS Line Color")
bosLineStyle = input.string("Dotted", title="BOS Line Style", options= )
bosLineStyleConst = bosLineStyle == "Solid" ? line.style_solid : bosLineStyle == "Dotted" ? line.style_dotted : line.style_dashed
alertMode = input.string("MTF", title= "Enable/Disable for Any Alert() Function Call↓ Alert Status→", options= )
alertSupplyandDemand = input.bool(true, title= "Supply & Demand Zones")
alertHighsandLows = input.bool(true, title= "Swing Highs & Lows")
alertBoS = input.bool(true, title= "BoS")
alertMS = input.bool(true, title= "Market Shifts")
hhBackgroundColor = color.rgb(76, 175, 79, 100)
hhTextColor = color.green
lhBackgroundColor = color.rgb(0, 137, 123, 100)
lhTextColor = color.red
llBackgroundColor = color.rgb(255, 82, 82, 100)
llTextColor = color.red
hlBackgroundColor = color.rgb(255, 153, 0, 100)
hlTextColor = color.green
HtfOpen = request.security(syminfo.tickerid, htf, open)
HtfHigh = request.security(syminfo.tickerid, htf, high)
HtfLow = request.security(syminfo.tickerid, htf, low)
HtfClose = request.security(syminfo.tickerid, htf, close)
prevHtfHigh = request.security(syminfo.tickerid, htf, high )
prevHtfLow = request.security(syminfo.tickerid, htf, low )
isHTFBarClose = ta.change(HtfClose) != 0
// Track the bar_index of the current bar when HTF closes
var int HtfBarIndex = na
if isHTFBarClose
HtfBarIndex := bar_index
// === Initialization ===
var int lastSignal = 0 // 0 = none, 1 = bull, -1 = bear
var float runningLowestHigh = na
var float runningHighestLow = na
// Track engulfed ranges
var float engulfedHigh = na
var float engulfedLow = na
// === Step 1: Detect "starter" engulfing ===
starterBull = HtfClose < HtfOpen and HtfClose > HtfOpen and HtfClose > HtfHigh
starterBear = HtfClose > HtfOpen and HtfClose < HtfOpen and HtfClose < HtfLow
if lastSignal == 0
if starterBull
lastSignal := 1
runningHighestLow := HtfLow
engulfedHigh := HtfHigh
engulfedLow := HtfLow
else if starterBear
lastSignal := -1
runningLowestHigh := HtfHigh
engulfedHigh := HtfHigh
engulfedLow := HtfLow
// === Step 2: Update running references ===
if lastSignal == -1 // last was bearish → waiting for bullish
runningLowestHigh := na(runningLowestHigh) ? HtfHigh : math.min(runningLowestHigh, HtfHigh)
else if lastSignal == 1 // last was bullish → waiting for bearish
runningHighestLow := na(runningHighestLow) ? HtfLow : math.max(runningHighestLow, HtfLow)
// === Step 3: Check for new engulfment ===
newBull = lastSignal == -1 and not na(runningLowestHigh) and HtfClose > runningLowestHigh
newBear = lastSignal == 1 and not na(runningHighestLow) and HtfClose < runningHighestLow
var int lastBullIndex = na
var int lastBearIndex = na
if newBull
lastBullIndex := HtfBarIndex
// store engulfed candle values (the one we just broke over)
engulfedHigh := runningLowestHigh
engulfedLow := HtfLow // or HtfLow depending on how you define "engulfed"
if newBear
lastBearIndex := HtfBarIndex
engulfedLow := runningHighestLow
engulfedHigh := HtfHigh
// === Step 4: Confirm and flip state ===
if newBull
lastSignal := 1
runningLowestHigh := na
runningHighestLow := HtfLow
else if newBear
lastSignal := -1
runningHighestLow := na
runningLowestHigh := HtfHigh
// === Track Boxes ===
var box bullishBoxes = array.new()
var box bearishBoxes = array.new()
// === Mitigation Flags ===
var bool bullishMitigated = false
var bool bearishMitigated = false
var bool bullishBreak = false
var bool bearishBreak = false
// === Delete invalidated boxes ===
if deleteBrokenBoxes
if array.size(bullishBoxes) > 0
for i = array.size(bullishBoxes) - 1 to 0
boxItem = array.get(bullishBoxes, i)
if HtfClose < box.get_bottom(boxItem)
box.delete(boxItem)
array.remove(bullishBoxes, i)
if array.size(bearishBoxes) > 0
for i = array.size(bearishBoxes) - 1 to 0
boxItem = array.get(bearishBoxes, i)
if HtfClose > box.get_top(boxItem)
box.delete(boxItem)
array.remove(bearishBoxes, i)
// === Delete mitigated boxes (optional) ===
if deleteMitigatedBoxes
if array.size(bullishBoxes) > 0
for i = array.size(bullishBoxes) - 1 to 0
boxItem = array.get(bullishBoxes, i)
if HtfLow < box.get_top(boxItem)
bullishMitigated := true
box.delete(boxItem)
array.remove(bullishBoxes, i)
if array.size(bearishBoxes) > 0
for i = array.size(bearishBoxes) - 1 to 0
boxItem = array.get(bearishBoxes, i)
if HtfHigh > box.get_bottom(boxItem)
bearishMitigated := true
box.delete(boxItem)
array.remove(bearishBoxes, i)
if dimMitigatedBoxes
if array.size(bullishBoxes) > 0
for i = 0 to array.size(bullishBoxes) - 1
boxItem = array.get(bullishBoxes, i)
if HtfLow < box.get_top(boxItem)
bullishMitigated := true
box.set_bgcolor(boxItem, lighterBullishColor)
box.set_border_color(boxItem, lighterBullishColor)
if array.size(bearishBoxes) > 0
for i = 0 to array.size(bearishBoxes) - 1
boxItem = array.get(bearishBoxes, i)
if HtfHigh > box.get_bottom(boxItem)
bearishMitigated := true
box.set_bgcolor(boxItem, lighterBearishColor)
box.set_border_color(boxItem, lighterBearishColor)
// Peramters for boxes
zoneHigh = ta.highest(HtfHigh , x)
zoneLow = ta.lowest(HtfLow , x)
// Create new order blocks with adjusted alignment
if showBullishOrderBlocks and newBull
bullishBox = box.new(left= HtfBarIndex , right=HtfBarIndex + orderBlockDuration, top=zoneHigh, bottom=zoneLow, border_color=bullishBlockColor, bgcolor=bullishBlockColor)
array.push(bullishBoxes, bullishBox)
if showBearishOrderBlocks and newBear
bearishBox = box.new(left= HtfBarIndex , right=HtfBarIndex + orderBlockDuration, top=zoneHigh, bottom=zoneLow, border_color=bearishBlockColor, bgcolor=bearishBlockColor)
array.push(bearishBoxes, bearishBox)
// === Internal Structure Logic ===
var int bullishCount = 0
var int bearishCount = 0
var float lowestBullishPrice = na
var float highestBearishPrice = na
var float firstBullishOpen = na
var float firstBearishOpen = na
var int lastInternalShift = 0
var float lastBullishInternalShiftPrice = na
var float lastBearishInternalShiftPrice = na
var float currentSwingHigh = na
var int currentSwingHighIndex = na
var float currentSwingLow = na
var int currentSwingLowIndex = na
var float prevSwingHigh = na
var float prevSwingLow = na
var bool isHH = false
var bool isHL = false
var bool isLL = false
var bool isLH = false
var bool isLiquiditySweep = false
var float lastOpposingLow = na // For HH
var float lastOpposingHigh = na // For LL
var bool internalShiftBullish = false
var bool internalShiftBearish = false
if ((internalShiftMode == "Engulfment") or (internalShiftMode == "Market Shift (Engulfment)"))
internalShiftBullish := newBull
internalShiftBearish := newBear
allowInternalShiftBearish = internalShiftBearish and lastInternalShift != -1
allowInternalShiftBullish = internalShiftBullish and lastInternalShift != 1
var bool plotBearishInternalShift = false
var bool plotBullishInternalShift = false
// === Determine Internal Shift Based on User Input ===
plotBearishInternalShift := false
plotBullishInternalShift := false
if allowInternalShiftBearish
plotBearishInternalShift := true
lastInternalShift := -1
if allowInternalShiftBullish
plotBullishInternalShift := true
lastInternalShift := 1
// === Plot internal shift markers ==
plotshape(plotBullishInternalShift, title="Bullish Internal Shift", location=location.belowbar, color=internalShiftColor, style=shape.triangleup, size=size.tiny)
plotshape(plotBearishInternalShift, title="Bearish Internal Shift", location=location.abovebar, color=internalShiftColor, style=shape.triangledown, size=size.tiny)
// === Highest High Between Alternate Bearish Break and Last Bullish Break (Safe) ===
var float localHigh = na
var int localHighIndex = na
maxHistory = 10000
if plotBearishInternalShift and ((internalShiftMode == "Engulfment") or (internalShiftMode == "Market Shift (Engulfment)"))
float highestHigh = na
int highestIndex = na
int startIndex = math.max(lastBullIndex, bar_index - maxHistory)
int endIndex = HtfBarIndex
for i = startIndex to endIndex
int lookback = bar_index - i // Convert i to relative offset for series access
if lookback >= 0 and lookback < maxHistory and not na(HtfHigh )
if na(highestHigh) or HtfHigh > highestHigh
highestHigh := HtfHigh
highestIndex := i
localHigh := highestHigh
localHighIndex := highestIndex
// === Lowest Low Between Alternate Bullish Break and Last Bearish Break (Safe) ===
var float localLow = na
var int localLowIndex = na
if plotBullishInternalShift and ((internalShiftMode == "Engulfment") or (internalShiftMode == "Market Shift (Engulfment)"))
float lowestLow = na
int lowestIndex = na
int startIndex = math.max(lastBearIndex, HtfBarIndex - maxHistory)
int endIndex = bar_index
for i = startIndex to endIndex
int lookback = bar_index - i // Convert i to relative offset
if lookback >= 0 and lookback < maxHistory and not na(HtfLow )
if na(lowestLow) or HtfLow < lowestLow
lowestLow := HtfLow
lowestIndex := i
localLow := lowestLow
localLowIndex := lowestIndex
// === Track Last Non-Alternating Break of Structure (BoS) ===
var int lastBullishBoSBarNA = na
var int lastBearishBoSBarNA = na
var float lastBullishBoSPriceNA = na
var float lastBearishBoSPriceNA = na
var bool bullishBOSOccurred = false
var bool bearishBOSOccurred = false
var int lastLowIndex = na
var int lastHighIndex = na
var float lastSwingHigh = na
var float lastSwingLow = na
// Reset flags
var bool canBreakBullish = true
var bool canBreakBearish = true
// BoS Conditions (non-alternating)
bullishBoS = canBreakBullish and HtfOpen < localHigh and HtfClose > localHigh
bearishBoS = canBreakBearish and HtfOpen > localLow and HtfClose < localLow
if bullishBoS and internalShiftMode == "Engulfment"
lastBullishBoSBarNA := bar_index
lastBullishBoSPriceNA := HtfClose
canBreakBullish := false // prevent further BoS on same localHigh
bullishBOSOccurred := true
line.new(x1=localHighIndex, y1=localHigh, x2=bar_index, y2=localHigh, color=bosBullishLineColor, width=zigzagLineWidth, style=bosLineStyleConst)
lastSwingHigh := na
if bearishBoS and internalShiftMode == "Engulfment"
lastBearishBoSBarNA := bar_index
lastBearishBoSPriceNA := HtfClose
canBreakBearish := false // prevent further BoS on same localLow
bearishBOSOccurred := true
line.new(x1=localLowIndex, y1=localLow, x2=bar_index, y2=localLow, color=bosBearishLineColor, width=zigzagLineWidth, style=bosLineStyleConst)
lastSwingLow := na
// Reset logic — allow new break only if local high/low changes
if ta.change(localHigh) != 0
canBreakBullish := true
if ta.change(localLow) != 0
canBreakBearish := true
// === Track Last MS Event ===
var int lastBullishBoSBar = na
var int lastBearishBoSBar = na
var float lastBullishBoSPrice = na
var float lastBearishBoSPrice = na
var bool SwingHighBOSOccurred = false
var bool SwingLowBOSOccurred = false
var int lastSwingLowIndex = na
var int lastSwingHighIndex = na
var float lastSSwingHigh = na
var float lastSSwingLow = na
// Track last BoS type: 1 = bullish, -1 = bearish, 0 = none yet
var int lastBoSType = 0
// === Track Last MS Type ===
var int lastMSType = na // 1 = bullish, -1 = bearish
// === MS Detection Logic ===
rawBullishMS = HtfClose > localHigh
rawBearishMS = HtfClose < localLow
// === Enforce Alternation ===
canBullishMS = na(lastMSType) or lastMSType == -1
canBearishMS = na(lastMSType) or lastMSType == 1
bullishMS = rawBullishMS and canBullishMS
bearishMS = rawBearishMS and canBearishMS
plotshape(bullishMS, title="Bullish Market Shift", location=location.belowbar, color=zigzagLineColor, style=shape.triangleup, size=size.tiny)
plotshape(bearishMS, title="Bearish Market Shift", location=location.abovebar, color=zigzagLineColor, style=shape.triangledown, size=size.tiny)
// === Update Last MS Type and BoS Bars ===
if bullishMS
lastMSType := 1
lastBullishBoSBar := bar_index
if bearishMS
lastMSType := -1
lastBearishBoSBar := bar_index
// === Lowest Low Between Last Bearish MS and This Bullish MS ===
var float msLocalLow = na
var int msLocalLowIndex = na
msMaxHistory = 5000
if bullishMS
float msLowestLow = na
int msLowestIndex = na
int msStartIndex = na(lastBearishBoSBar) ? bar_index - msMaxHistory : lastBearishBoSBar
int msEndIndex = bar_index // safer than using HtfBarIndex unless defined
for i = msStartIndex to msEndIndex
int msLookback = bar_index - i
if msLookback >= 0 and msLookback < msMaxHistory and not na(HtfLow )
if na(msLowestLow) or HtfLow < msLowestLow
msLowestLow := HtfLow
msLowestIndex := i
msLocalLow := msLowestLow
msLocalLowIndex := msLowestIndex
// === Highest High Between Last Bullish MS and This Bearish MS ===
var float msLocalHigh = na
var int msLocalHighIndex = na
if bearishMS
float msHighestHigh = na
int msHighestIndex = na
int msStartIndex = na(lastBullishBoSBar) ? bar_index - msMaxHistory : lastBullishBoSBar
int msEndIndex = bar_index
for i = msStartIndex to msEndIndex
int msLookback = bar_index - i
if msLookback >= 0 and msLookback < msMaxHistory and not na(HtfHigh )
if na(msHighestHigh) or HtfHigh > msHighestHigh
msHighestHigh := HtfHigh
msHighestIndex := i
msLocalHigh := msHighestHigh
msLocalHighIndex := msHighestIndex
// === Persistent variables for multiple line handling ===
var line zigzagLines = array.new()
var int lastBearishShiftBar = na
var int lastBullishShiftBar = na
var float lastZigzagPrice = na
var string lastSwingType = ""
// Save shift bar indices
if plotBearishInternalShift
lastBearishShiftBar := bar_index
if plotBullishInternalShift
lastBullishShiftBar := bar_index
// Bearish shift followed by Bullish shift → Track lowest low
if plotBullishInternalShift and internalShiftMode == "Engulfment"
// Plot zigzag line
// Plot zigzag line for LL and HL separately
if not na(prevSwingLow)
if localLow < prevSwingLow // LL
if zigzagLineStyle == "Solid"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
else // LH
if zigzagLineStyle == "Solid"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=localHighIndex, y1=localHigh, x2=localLowIndex, y2=localLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
// Update swing low and plot label (HL or LL)
if not na(prevSwingLow)
isLL := not na(prevSwingLow) and localLow < prevSwingLow
isHL := not na(prevSwingLow) and localLow > prevSwingLow
if isLL
if bearishBOSOccurred
label.new(localLowIndex, localLow, "LL", color=llBackgroundColor, style=label.style_label_up, textcolor=llTextColor, size=size.small)
isLiquiditySweep := false // Definitely not a sweep if BOS occurred
else
label.new(localLowIndex, localLow, "LS", color=color.rgb(155, 39, 176, 100), style=label.style_label_up, textcolor=color.orange, size=size.small)
isLiquiditySweep := true
else
isLiquiditySweep := false // Reset only if not LL
lastOpposingHigh := prevSwingHigh
bearishBOSOccurred := false
if isHL
label.new(localLowIndex, localLow, "HL", color=hlBackgroundColor, style=label.style_label_up, textcolor=hlTextColor, size=size.small)
lastOpposingHigh := prevSwingHigh
bearishBOSOccurred := false
prevSwingLow := localLow
lastZigzagPrice := localLow
lastSwingLow := localLow
lastLowIndex := localLowIndex
lastBearishShiftBar := bar_index
if bullishMS and internalShiftMode == "Market Shift (Engulfment)"
// Plot zigzag line
// Plot zigzag line for LL and HL separately
if not na(prevSwingLow)
if msLocalLow < prevSwingLow // LL
if zigzagLineStyle == "Solid"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
else // LH
if zigzagLineStyle == "Solid"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=msLocalHighIndex, y1=msLocalHigh, x2=msLocalLowIndex, y2=msLocalLow, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
// Update swing low and plot label (HL or LL)
if not na(prevSwingLow)
isLL := not na(prevSwingLow) and msLocalLow < prevSwingLow
isHL := not na(prevSwingLow) and msLocalLow > prevSwingLow
if isLL
label.new(msLocalLowIndex, msLocalLow, "LL", color=llBackgroundColor, style=label.style_label_up, textcolor=llTextColor, size=size.small)
if isHL
label.new(msLocalLowIndex, msLocalLow, "HL", color=hlBackgroundColor, style=label.style_label_up, textcolor=hlTextColor, size=size.small)
lastOpposingHigh := prevSwingHigh
SwingLowBOSOccurred := false
prevSwingLow := msLocalLow
lastZigzagPrice := msLocalLow
lastSwingLow := msLocalLow
lastLowIndex := msLocalLowIndex
lastBearishShiftBar := bar_index
//========================================================================================
if plotBearishInternalShift and internalShiftMode == "Engulfment"
// Plot zigzag line
if not na(prevSwingHigh)
if localHigh > prevSwingHigh // HH
if zigzagLineStyle == "Solid"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
else // LH
if zigzagLineStyle == "Solid"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=localLowIndex, y1=localLow, x2=localHighIndex, y2=localHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
// Update swing high and plot label (HH or LH)
if not na(prevSwingHigh)
isHH := not na(prevSwingHigh) and localHigh > prevSwingHigh
isLH := not na(prevSwingHigh) and localHigh < prevSwingHigh
if isHH
if bullishBOSOccurred
label.new(localHighIndex, localHigh, "HH", color=hhBackgroundColor, style=label.style_label_down, textcolor=hhTextColor, size=size.small)
isLiquiditySweep := false
else
label.new(localHighIndex, localHigh, "LS", color=color.rgb(155, 39, 176, 100), style=label.style_label_down, textcolor=color.orange, size=size.small)
isLiquiditySweep := true
else
isLiquiditySweep := false
bullishBOSOccurred := false
if isLH
label.new(localHighIndex, localHigh, "LH", color=lhBackgroundColor, style=label.style_label_down, textcolor=lhTextColor, size=size.small)
lastOpposingLow := prevSwingLow
bullishBOSOccurred := false
prevSwingHigh := localHigh
lastZigzagPrice := localHigh
lastSwingHigh := localHigh
lastHighIndex := localHighIndex
lastBullishShiftBar := bar_index
if bearishMS and internalShiftMode == "Market Shift (Engulfment)"
// Plot zigzag line
if not na(prevSwingHigh)
if msLocalHigh > prevSwingHigh // HH
if zigzagLineStyle == "Solid"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
else // LH
if zigzagLineStyle == "Solid"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
else if zigzagLineStyle == "Dotted"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
else if zigzagLineStyle == "Dashed"
line.new(x1=msLocalLowIndex, y1=msLocalLow, x2=msLocalHighIndex, y2=msLocalHigh, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
// Update swing high and plot label (HH or LH)
if not na(prevSwingHigh)
isHH := not na(prevSwingHigh) and msLocalHigh > prevSwingHigh
isLH := not na(prevSwingHigh) and msLocalHigh < prevSwingHigh
if isHH
label.new(msLocalHighIndex, msLocalHigh, "HH", color=hhBackgroundColor, style=label.style_label_down, textcolor=hhTextColor, size=size.small)
SwingHighBOSOccurred := false
if isLH
label.new(msLocalHighIndex, msLocalHigh, "LH", color=lhBackgroundColor, style=label.style_label_down, textcolor=lhTextColor, size=size.small)
lastOpposingLow := prevSwingLow
SwingHighBOSOccurred := false
prevSwingHigh := msLocalHigh
lastZigzagPrice := msLocalHigh
lastSwingHigh := msLocalHigh
lastHighIndex := msLocalHighIndex
lastBullishShiftBar := bar_index
// === Alert Conditions ===
alertcondition(newBull, title="New Supply Zone", message="New supply zone available.")
alertcondition(newBear, title="New Demand Zone", message="New demand zone available.")
alertcondition(plotBullishInternalShift, title="Bullish Internal Shift (All Lows)", message="Bullish Internal Shift detected! Check Swing Low.")
alertcondition(plotBearishInternalShift, title="Bearish Internal Shift (All Highs)", message="Bearish Internal Shift detected! Check Swing High.")
alertcondition(bullishBOSOccurred, title="Bullish Break of Structure", message="Bullish BoS detected.")
alertcondition(bearishBOSOccurred, title="Bearish Break of Structure", message="Bearish BoS detected.")
alertcondition(bullishMS, title="Bullish Market Shift", message="Bullish market shift detected.")
alertcondition(bearishMS, title="Bearish Market Shift", message="Bearish market shift detected.")
alertcondition(isHH and plotBearishInternalShift and not isLiquiditySweep, title="Higher High (HH)", message="Higher High (HH) detected")
alertcondition(isHL and plotBullishInternalShift, title="Higher Low (HL)", message="Higher Low (HL) detected")
alertcondition(isLL and plotBullishInternalShift and not isLiquiditySweep, title="Lower Low (LL)", message="Lower Low (LL) detected")
alertcondition(isLH and plotBearishInternalShift, title="Lower High (LH)", message="Lower High (LH) detected")
alertcondition((isLiquiditySweep and isLL and plotBullishInternalShift) or (isLiquiditySweep and isHH and plotBearishInternalShift), title="Liquidity Sweep (LS)", message="Liquidity Sweep (LS) detected")
// === Alerts ===
if alertMode == "LTF"
if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Higher High (HH) detected (LTF)", alert.freq_once_per_bar_close)
if isHL and plotBullishInternalShift and (alertHighsandLows == true)
alert("Higher Low (HL) detected (LTF)", alert.freq_once_per_bar_close)
if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Lower Low (LL) detected (LTF)" , alert.freq_once_per_bar_close)
if isLH and plotBearishInternalShift and (alertHighsandLows == true)
alert("Lower High (LH) detected (LTF)", alert.freq_once_per_bar_close)
if ((isLiquiditySweep and isLL and plotBullishInternalShift) or (isLiquiditySweep and isHH and plotBearishInternalShift)) and (alertHighsandLows == true)
alert("Liquidity Sweep (LS) detected (LTF)", alert.freq_once_per_bar_close)
if newBear and (alertSupplyandDemand == true)
alert("New supply zone available. (LTF)", alert.freq_once_per_bar_close)
if newBull and (alertSupplyandDemand == true)
alert("New demand zone available. (LTF)", alert.freq_once_per_bar_close)
if bullishBOSOccurred and (alertBoS == true)
alert("Bullish BoS detected. (LTF)", alert.freq_once_per_bar_close)
if bearishBOSOccurred and (alertBoS == true)
alert("Bearish BoS detected. (LTF)", alert.freq_once_per_bar_close)
if bullishMS and (alertMS == true)
alert("Bullish market shift detected (LTF).", alert.freq_once_per_bar_close)
if bearishMS and (alertMS == true)
alert("Bearish market shift detected (LTF).", alert.freq_once_per_bar_close)
if alertMode == "MTF"
if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Higher High (HH) detected (MTF)", alert.freq_once_per_bar_close)
if isHL and plotBullishInternalShift and (alertHighsandLows == true)
alert("Higher Low (HL) detected (MTF)", alert.freq_once_per_bar_close)
if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Lower Low (LL) detected (MTF)" , alert.freq_once_per_bar_close)
if isLH and plotBearishInternalShift and (alertHighsandLows == true)
alert("Lower High (LH) detected (MTF)", alert.freq_once_per_bar_close)
if ((isLiquiditySweep and isLL and plotBullishInternalShift) or (isLiquiditySweep and isHH and plotBearishInternalShift)) and (alertHighsandLows == true)
alert("Liquidity Sweep (LS) detected (MTF)", alert.freq_once_per_bar_close)
if newBear and (alertSupplyandDemand == true)
alert("New supply zone available. (MTF)", alert.freq_once_per_bar_close)
if newBull and (alertSupplyandDemand == true)
alert("New demand zone available. (MTF)", alert.freq_once_per_bar_close)
if bullishBOSOccurred and (alertBoS == true)
alert("Bullish BoS detected. (MTF)", alert.freq_once_per_bar_close)
if bearishBOSOccurred and (alertBoS == true)
alert("Bearish BoS detected. (MTF)", alert.freq_once_per_bar_close)
if bullishMS and (alertMS == true)
alert("Bullish market shift detected (MTF).", alert.freq_once_per_bar_close)
if bearishMS and (alertMS == true)
alert("Bearish market shift detected (MTF).", alert.freq_once_per_bar_close)
if alertMode == "HTF"
if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Higher High (HH) detected (HTF)", alert.freq_once_per_bar_close)
if isHL and plotBullishInternalShift and (alertHighsandLows == true)
alert("Higher Low (HL) detected (HTF)", alert.freq_once_per_bar_close)
if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
alert("Lower Low (LL) detected (HTF)" , alert.freq_once_per_bar_close)
if isLH and plotBearishInternalShift and (alertHighsandLows == true)
alert("Lower High (LH) detected (HTF)", alert.freq_once_per_bar_close)
if ((isLiquiditySweep and isLL and plotBullishInternalShift) or (isLiquiditySweep and isHH and plotBearishInternalShift)) and (alertHighsandLows == true)
alert("Liquidity Sweep (LS) detected (HTF)", alert.freq_once_per_bar_close)
if newBear and (alertSupplyandDemand == true)
alert("New supply zone available. (HTF)", alert.freq_once_per_bar_close)
if newBull and (alertSupplyandDemand == true)
alert("New demand zone available. (HTF)", alert.freq_once_per_bar_close)
if bullishBOSOccurred and (alertBoS == true)
alert("Bullish BoS detected. (HTF)", alert.freq_once_per_bar_close)
if bearishBOSOccurred and (alertBoS == true)
alert("Bearish BoS detected. (HTF)", alert.freq_once_per_bar_close)
if bullishMS and (alertMS == true)
alert("Bullish market shift detected (HTF).", alert.freq_once_per_bar_close)
if bearishMS and (alertMS == true)
alert("Bearish market shift detected (HTF).", alert.freq_once_per_bar_close)
Market Dashboard: Vol %, Trend, ATR (Custom Colors)Market Dashboard: Volume %, Trend & ATR
This indicator provides a compact at-a-glance market dashboard directly on your chart, helping you quickly assess order flow bias, trend direction, and volatility without clutter.
What it shows:
Bull vs Bear Volume % over a customizable lookback, with flexible doji handling (ignore, assign, or split).
Trend direction using EMA crossovers on both the current timeframe and a higher timeframe for context.
ATR value with an optional percentage-of-price display to gauge volatility and position sizing.
Key features:
Fully customizable colors, text size, and table position
Higher timeframe trend confirmation
Clean table design that updates on the latest bar only
Ideal for traders who want quick confirmation before entries, improved market bias awareness, and better risk/volatility context while scalping or swing trading.
Trend Double Pullback [Stable 20]v1.0Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double
Smart Scalper Pro Template + VWAP
📌 Author
Garry Evans
Independent system developer focused on:
Risk-first automation
Market structure & liquidity behavior
Discipline, consistency, and capital preservation
“The edge isn’t the market — it’s the man who survives it.”
⚙️ Risk Management & Position Sizing
The script is built around capital protection, not signal frequency.
Risk logic includes:
Fixed or dynamic risk per trade
Market-adaptive position sizing
Session-based trade limits
Daily trade caps and auto-lockout protection
Volatility-aware sizing (futures & crypto)
⚠️ Profit is pursued only after risk is controlled.
📊 Track Record
Backtested across multiple market environments
Forward-tested and actively used by the author
Real-account trades are logged where platform rules allow
Results vary by market, timeframe, and user-defined risk settings.
🌍 Supported Markets
Designed to work across all liquid markets, including:
Stocks
Crypto (spot & futures)
Options (signal-based framework)
Futures (indices, metals, crypto futures)
The system adapts to volatility and structure — it is not market-specific.
⚖️ Leverage
Leverage is not required
If used, leverage is fully user-controlled
Risk logic scales exposure conservatively
No martingale.
No revenge sizing.
No over-exposure logic.
🧪 Backtesting
✔ Yes
Strategy logic has been backtested
Filters reduce chop, noise, and forced trades
Focus on drawdown control over curve-fitting
🛠 Support
✔ Yes
Direct author support
Ongoing improvements and updates
Feature refinement based on real usage and feedback
👥 Community
✔ Yes
Private user access
High-quality feedback environment
No public signal spam or hype-driven chat rooms
⏳ Trial Period
✔ Yes
Limited trial access available
Designed for evaluation only
Trial users do not receive full feature access
🚫 Who This Script Is NOT For
This system is not for:
Traders looking for guaranteed profits
Users expecting copy-paste “signal calls”
Over-leveraged gamblers
Those unwilling to follow risk rules
Anyone seeking overnight results
This is a discipline and automation tool, not a shortcut.
🧠 Final Positioning
This is not a signal service.
This is a risk-controlled execution framework designed to:
Enforce discipline
Reduce emotional trading
Protect capital during bad market conditions
Scale responsibly during favorable ones
Renko Top 2 Picker### **1s Renko Momentum Scanner (HMA Zero-Lag Edition)**
This custom TradingView indicator is engineered specifically for high-frequency Renko traders. It solves the critical problem of identifying which major currency pair has the liquidity and directional inertia to sustain a fixed-brick Renko trend on a 1-second chart.
Because TradingView cannot screen 1-second data directly, this script acts as a "bridge," analyzing 1-minute and 5-minute flow metrics to probability-score the likely performance of a 1-second chart.
---
### **Core Logic & Assumptions**
1. **The "Engine" (HMA 300):**
* **Logic:** The script uses a Hull Moving Average (HMA) with a length of 300 to smooth the scoring output.
* **Why:** On a 1-second chart, 300 bars equals 5 minutes of data. The HMA provides a "Zero-Lag" response, reacting instantly to new breakouts while ignoring the split-second noise that causes standard scanners to flicker.
2. **The "Minute Reset" Solution:**
* **Problem:** Standard scripts fail on 1s charts because metrics like "Current Volume" reset to zero at the start of every new minute (e.g., at 10:05:00), causing signals to crash.
* **Solution:** This script calculates momentum using a "Rolling Window" anchored to the *previous* minute's close and volume. This ensures the signal remains stable and tradable across the :59 to :00 second boundary.
3. **Renko-Specific Scoring:**
* **Displacement > Direction:** The script prioritizes *how far* price is moving (Displacement %) over simple direction. Renko bricks require physical distance to form; without displacement, you pay spread costs for a flat chart.
* **Liquidity Gating:** It ignores pairs with low relative volume. A 1-second Renko chart requires high institutional flow to form clean bricks without gapping.
---
### **Indicator Inputs**
* **Refresh Display (Seconds):**
* *Default: 5*
* Controls how often the text on your screen updates. Set this to 5 or 10 seconds to prevent the text from "dancing," allowing you to read the recommendation clearly.
* **Score Smoothing (HMA):**
* *Default: 300*
* The "Memory" of the scanner.
* **300:** Represents a 5-minute lookback. Recommended for most 1s scalping to identify established trends.
* **120:** Represents a 2-minute lookback. Use this only if you want to catch breakouts aggressively and accept more false signals.
* **Table Position:**
* *Default: Bottom Right*
* Choose where the scanner panel appears on your chart to avoid covering your Renko price action.
* **Major Pairs:**
* *Defaults: EURUSD, GBPUSD, USDJPY, USDCHF, AUDUSD, USDCAD, NZDUSD*
* These fields are pre-filled with the standard "FX:" prefix. **Crucial:** If your broker uses suffixes (e.g., "EURUSD.pro" or "EURUSDm"), you must update these inputs to match your broker's specific symbol format, or the scanner will return "N/A".
---
### **How to Interpret the Output**
The panel displays a **Primary** and **Secondary** recommendation.
* **Green Background:** The pair has a "Strong" score (> 4.0). This indicates high probability conditions for 1s Renko trend following.
* **Gray Background:** The pair is the "best of the bunch," but overall market momentum is weak. Exercise caution, as the 1s chart may be choppy.






















