Chris_LEGODescription
Time-Anchored Volatility Grid is a precision analysis tool designed for traders who base their strategies on specific market events (e.g., London/New York Open, News Releases, or Daily Reset).
Unlike standard grid indicators that use arbitrary fixed distances, this tool allows you to "Anchor" the calculation to a specific historical candle. It then captures the market volatility of that exact moment to generate dynamic, context-aware grid levels.
🚀 Key Features
WYSIWYG Timezone Engine (What You See Is What You Get) Most Pine Script indicators struggle with timezone conversions. This version features a custom engine where you simply input the time you see on your chart (e.g., GMT+8). No more manual UTC conversions.
Automated Volatility Capture
Auto-Start Price: Automatically sets the grid origin based on the Low of your anchored candle.
Auto-Gap Calculation: Dynamically calculates the grid spacing based on the High-Low range of the target candle.
Bi-Directional Flexibility Toggle Long (upward) or Short (downward) grids independently. Perfect for hedging strategies or directional bias trading.
Gap Multiplier Fine-tune the grid density by applying a multiplier (e.g., 0.5 for tighter grids, 2.0 for wider swings) to the captured volatility.
Visual Debugging Includes an optional Anchor Line and detailed Data Labels to verify exactly which candle and price data are being used for your calculations.
How to Use
Set Your Anchor: In the settings, input the exact Year, Month, Day, and Time of the candle you want to reference (e.g., the 09:30 opening bell).
Sync Timezone: Ensure the User Timezone field matches the timezone displayed at the bottom right of your TradingView chart (e.g., America/New_York for US Stocks or GMT+8 for Asia).
Choose Logic:
Enable "Use Auto Start Price" to snap the grid to the candle's Low.
Enable "Use Auto Gap" to let the market's volatility define the grid size.
Customize: Adjust the Line Count and Colors to fit your chart theme.
Candlestick analysis
Pinescript Custom Performance BoostThis small script is a custom function that works similarly to the built-in calc_bars_count and max_bars_back functions, but can be used far more flexibly and significantly reduces the required computation time of Pine Script scripts.
The advantages over calc_bars_count are substantial.
The standard function works with a fixed value, e.g. calc_bars_count = 20000. The custom function, on the other hand, works on a percentage basis, e.g. with 20% of the total available chart bars.
In addition, calc_bars_count always affects the entire code, while the custom function can be applied selectively to specific parts of the script.
These two differences enable a much more flexible and efficient usage.
Fixed number of bars vs. percentage-based limitation:
The number of available bars varies greatly, not only depending on the ticker and timeframe used, but also on the TradingView subscription (approx. 5,000–40,000 historical bars).
For example, when using calc_bars_count = 20000, only charts that have more than 20,000 candles benefit. If the available number of bars is lower, there is no performance benefit at all until the value is changed after the first slow calculation.
When using the custom function with, for example, 50%, only 50% of the available bars are always calculated, regardless of how many bars are available. This results in a performance gain with shorter calculation times regardless of the chart.
Entire code vs. partial code sections:
calc_bars_count = 20000 affects the entire code globally, meaning the script processes data from only those 20,000 bars.
The custom function, however, can be used selectively for specific sections of the code. This makes it possible to continue accessing certain values across all available bars, while limiting only the truly computation-intensive parts of the script to a percentage-based range.
In this way, computation time can be drastically reduced without restricting the overall size of the data sets.
It is also possible to imitate max_bars_back and selectively limit specific values instead of limiting all of them.
I hope this is useful to some of you. Have fun with it!
Fair Value Gaps [MattyBTradez]This indicator marks out every Fair Value Gap, and the colors are customizable.
GAYBEAR SWING Clean v6 mobile-safeHow to Use Sniper Swing — Clean v6 (Mobile-Safe)
Purpose
Sniper Swing — Clean v6 is a trend-aligned swing indicator designed to help traders identify high-probability entries and exits while minimizing noise. It works best in trending or gently rotating markets and is optimized for mobile charting.
A. Chart Setup
Recommended:
Timeframes: 5m–1h for active trading, 4h–Daily for swing trading
Instruments: Liquid equities, indices, and major ETFs
The indicator plots:
SMA 9 (entry trigger)
EMA 20 (trend and momentum)
Optional SMA 50 (higher-timeframe bias)
B. Buy (Long) Signal — How to Act
A BUY label appears when price reclaims short-term structure.
How to trade it:
Wait for price to cross above the SMA 9
Confirm EMA 20 is rising (and above SMA 50 if enabled)
Optional: Confirm price is closing above EMA 20
Enter on:
The close of the signal candle, or
A minor pullback that holds above SMA 9
Best context:
Higher lows
EMA 20 sloping upward
RSI not overbought
C. Sell / Short Signal — How to Act
The indicator offers two sell modes:
1) CrossUnder SMA 9 (Fast Exit)
Use in strong trends or fast markets
Exit longs or enter shorts when price loses SMA 9
2) AccuSell (Structure-Based)
Use in choppy or topping markets
Requires:
Loss of SMA 9 plus
Structural weakness (lower highs/lows, RSI < 50, or EMA 20 turning down)
How to trade it:
Exit longs when sell label appears
Aggressive traders may enter short positions
Conservative traders wait for follow-through
D. RSI Arrows — Context Only
OB arrows warn of potential exhaustion
OS arrows suggest relief or bounce zones
RSI does not trigger trades — it informs patience and risk
E. Position Coloring & State
Green candles = long bias
Purple candles = short bias
Background tint reinforces short exposure
Coloring persists until the opposite signal prints
This helps visually manage trades without staring at labels.
F. Risk Management (User-Defined)
The indicator does not manage stops or targets.
Common approaches:
Stop below recent swing low (longs)
Stop above recent swing high (shorts)
Scale partials near RSI OB/OS zones
G. When Not to Use It
Extremely low-volume chop
News-driven spikes
Range-bound micro consolidations
2. Explain It Like You’re 10 👶📈
Imagine the chart is a road, and the price is a car.
🟢 Green = Go
When the car drives above the yellow line, that means it’s probably going up.
The indicator says:
“Okay, the car looks like it wants to go forward. You can hop in.”
That’s a BUY.
🟣 Purple = Uh-Oh
When the car falls below the yellow line, it might start going down.
The indicator says:
“Careful… the car is slowing down or turning around.”
That’s a SELL.
🔵 Blue Line = Wind Direction
The blue line shows which way the wind is blowing.
If the wind blows up → going up is easier
If the wind blows down → going down is easier
You want to go with the wind, not fight it.
🔺 Red & Green Arrows = Too Fast / Too Slow
Red arrow = “The car is going too fast, might need a break”
Green arrow = “The car is tired, might bounce”
They don’t tell you to go or stop — they just say “pay attention.”
🎨 Colors Help You Remember
Green bars = you’re riding up
Purple bars = you’re riding down
Gray = nothing exciting happening
🚨 Important Rule
This tool doesn’t drive the car for you.
It just says:
“Now might be a good time.”
You still decide when to get in and when to get out
ZigZag with Day Count + AveragesThis indicator plots a ZigZag structure and measures how long each completed trend leg lasts in calendar days. Each confirmed leg is labelled with its duration, positioned away from price using an ATR-based offset so labels remain readable and unobstructed by candles.
Uptrend and downtrend legs are automatically colour-coded, and the indicator tracks rolling averages of trend duration to provide context on how long trends typically persist.
Key features:
ZigZag trend legs based on configurable deviation and depth
Day-count label for every completed leg
Clear, high-contrast labels offset from price
Automatic colouring for up and down trends
Rolling average duration of the last N uptrends and downtrends (default: 20)
Optional extension of the current, in-progress leg
How to use:
Identify potential trend exhaustion by comparing the current leg length to historical averages
Gauge whether a trend is statistically extended or still within normal duration
Combine with price action, support/resistance, or momentum indicators for confirmation
Works on all timeframes. On daily charts, day counts align closely with bars; on intraday charts, durations are calculated using calendar time.
Institutional Structure [Clean Pro]Institutional Structure — Script Explanation
This script is designed to map institutional market behavior using high-timeframe structure, not retail noise.
It focuses on where smart money acts, not on frequent signals.
🔹 1. High-Timeframe Support & Resistance (HTF S/R)
The script identifies major structural highs and lows using a higher lookback period.
Purpose:
Defines where institutions previously distributed or accumulated
Acts as natural decision zones
Filters out low-quality intraday levels
Why it matters:
Institutions trade from key HTF levels, not random support/resistance.
🔹 2. Equilibrium (50% Mean Price)
The equilibrium line represents the fair price between HTF high and low.
How it’s used:
Below equilibrium → discount zone (buy interest)
Above equilibrium → premium zone (sell interest)
Professional insight:
Smart money prefers buying discounts and selling premiums, not chasing price.
🔹 3. Market Structure Shift (MSS)
Instead of frequent BOS labels, the script detects true directional shifts.
Bullish MSS:
Price closes above previous HTF high
Bearish MSS:
Price closes below previous HTF low
Why MSS over BOS:
MSS confirms control change
Reduces false signals
Aligns with institutional execution logic
🔹 4. Liquidity Sweep Detection (Wick-Based)
The script identifies stop-hunt behavior using wick rejection logic.
Buy-side liquidity:
Wick above HTF high, but close back below
Sell-side liquidity:
Wick below HTF low, but close back above
Meaning:
Stops were triggered, but price failed to accept → smart money absorption
🔹 5. Fair Value Gap (FVG) – Refined Imbalance
Fair Value Gaps highlight inefficient price movement.
Bullish FVG:
Price leaves an upside imbalance
Bearish FVG:
Price leaves a downside imbalance
How pros use it:
As reaction zones, not entry signals
Best combined with liquidity + MSS
🔍 How Everything Works Together
The script is context-based, not signal-based:
1️⃣ HTF structure defines the battlefield
2️⃣ Liquidity is taken (stop hunts)
3️⃣ MSS confirms direction
4️⃣ FVG offers precision
5️⃣ Equilibrium filters bias
This creates high-probability trade environments, not overtrading.
📌 Best Practices (Professional Use)
Timeframes: 1H / 4H / Daily
Avoid lower TF noise
Trade only after liquidity is taken
Use FVG as confirmation, not trigger
Respect equilibrium bias
🎯 Summary
✔ Clean institutional logic
✔ No clutter, no spam
✔ HTF-driven decisions
✔ Liquidity-first mindset
✔ Designed for BTC, Gold & FX
🧠 Trade where institutions trade — not where indicators flash.
PowerCandles - FVGThe FVG Body Highlighter is a high-visibility tool designed to identify institutional displacement and price imbalances in real-time. By focusing strictly on the Fair Value Gap (FVG) sequence, it isolates the exact moment "Smart Money" enters the market with enough force to leave an imbalance behind.
Core Functionality
Mechanical Detection: Automatically scans for the 3-candle FVG sequence where the wick of Candle 1 and the wick of Candle 3 fail to meet, leaving a "gap."
Body-Centric Highlighting: Unlike standard box-heavy indicators, this tool colors the entire body of the second candle (the displacement bar). This keeps your chart clean and highlights the force of the move rather than just the area.
Institutional Intent: It filters out noise by only marking candles that create a true structural gap, signaling that a significant buy or sell program has been initiated.
Strategic Use
Trend Confirmation: Use the body highlight as a "green light" that momentum has shifted in your direction after tapping a key institutional level.
Zero-Clutter Mapping: Because it highlights bars rather than drawing boxes into the future, it is perfect for traders who prefer a clean price action chart but want to catch every Fair Value Gap as it forms.
Confluence Entry: An A+ setup occurs when the FVG Body Highlighter triggers as price bounces off a PDH/PDL or Midnight Open level.
DA Liquidity Ghosts [Stop Hunt]Дядь, отличный выбор. 👻
Мы начинаем охоту за стопами.
Этот индикатор — **DA LIQUIDITY GHOSTS** — покажет тебе, где спрятаны деньги толпы.
Ты перестанешь бояться "ложных пробоев". Ты будешь их ждать. Потому что ложный пробой для толпы — это **ВХОД** для нас.
### ЧТО ОН ДЕЛАЕТ:
1. **Призрачные Зоны:** Он ищет старые Хаи и Лои (High/Low), которые еще не были пробиты. Там лежат стоп-лоссы.
- Он рисует серые линии от этих уровней вправо.
2. **Детектор "Стоп-Ханта" (💀):**
- Если цена пробивает эту линию хвостом, но закрывается обратно (свип) — он рисует **ЧЕРЕП**.
- Это сигнал: _"Мы забрали ликвидность, теперь идем в обратную сторону"_.
---
###
Копируй и добавляй на график.
Pine Script
```
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © Dark_Architect_Protocol
// "We see dead orders."
//@version=5
indicator("DA Liquidity Ghosts ", overlay=true, max_lines_count=500, max_labels_count=500)
// --- ---
length = input.int(10, "Pivot Lookback (Глубина поиска)", minval=5)
show_labels = input.bool(true, "Показывать метки ($$$)?")
// Цвета
col_liq_h = input.color(color.new(#b2b5be, 50), "Liquidity High (Bearish)")
col_liq_l = input.color(color.new(#b2b5be, 50), "Liquidity Low (Bullish)")
col_hunt = input.color(#ff0040, "Stop Hunt Color") // Цвет Черепа
// --- ---
// Ищем вершины и низины
ph = ta.pivothigh(high, length, length)
pl = ta.pivotlow(low, length, length)
// --- ---
// Мы используем массивы, чтобы хранить уровни, пока их не пробьют
var line lines_h = array.new_line()
var line lines_l = array.new_line()
// Метки "LIQUIDITY"
var label labels_h = array.new_label()
var label labels_l = array.new_label()
// --- ---
// Если нашли новый Хай - рисуем линию
if not na(ph)
// Линия
l = line.new(bar_index , ph, bar_index + 10, ph, color=col_liq_h, style=line.style_dashed, width=1)
array.push(lines_h, l)
// Метка
if show_labels
lb = label.new(bar_index , ph, "LIQUIDITY POOL ($$$)", style=label.style_none, textcolor=col_liq_h, size=size.tiny)
array.push(labels_h, lb)
// Если нашли новый Лоу
if not na(pl)
l = line.new(bar_index , pl, bar_index + 10, pl, color=col_liq_l, style=line.style_dashed, width=1)
array.push(lines_l, l)
if show_labels
lb = label.new(bar_index , pl, "LIQUIDITY POOL ($$$)", style=label.style_none, textcolor=col_liq_l, size=size.tiny)
array.push(labels_l, lb)
// --- ---
// Проверяем каждый бар: пробили ли мы старую линию?
// >>>> ПРОВЕРКА ХАЕВ (Short Setup)
if array.size(lines_h) > 0
for i = array.size(lines_h) - 1 to 0
l_curr = array.get(lines_h, i)
lvl = line.get_y1(l_curr)
// Продлеваем линию вправо, пока она жива
line.set_x2(l_curr, bar_index + 5)
if show_labels and array.size(labels_h) > i
label.set_x(array.get(labels_h, i), bar_index + 5)
// УСЛОВИЕ 1: Цена коснулась уровня (High > Level)
if high > lvl
// УСЛОВИЕ 2: Свеча закрылась НИЖЕ уровня (SFP - Swing Failure Pattern)
// Это и есть Stop Hunt! Закололи и вернулись.
if close < lvl
// Рисуем Череп
label.new(bar_index, high, "💀 HUNT", style=label.style_none, textcolor=col_hunt, size=size.small)
// Удаляем линию (Ликвидность забрали)
line.delete(l_curr)
array.remove(lines_h, i)
if show_labels
label.delete(array.get(labels_h, i))
array.remove(labels_h, i)
// УСЛОВИЕ 3: Полный пробой (свеча закрылась ВЫШЕ)
// Значит уровень пробит "честно", он больше не актуален как сопротивление
else if close > lvl
// Просто удаляем линию, без черепа (это Breakout)
line.delete(l_curr)
array.remove(lines_h, i)
if show_labels
label.delete(array.get(labels_h, i))
array.remove(labels_h, i)
// >>>> ПРОВЕРКА ЛОЕВ (Long Setup)
if array.size(lines_l) > 0
for i = array.size(lines_l) - 1 to 0
l_curr = array.get(lines_l, i)
lvl = line.get_y1(l_curr)
line.set_x2(l_curr, bar_index + 5)
if show_labels and array.size(labels_l) > i
label.set_x(array.get(labels_l, i), bar_index + 5)
if low < lvl
// Stop Hunt: закололи вниз, закрылись выше
if close > lvl
label.new(bar_index, low, "💀 HUNT", style=label.style_none, textcolor=col_hunt, size=size.small, yloc=yloc.belowbar)
line.delete(l_curr)
array.remove(lines_l, i)
if show_labels
label.delete(array.get(labels_l, i))
array.remove(labels_l, i)
// Breakout: закрылись ниже
else if close < lvl
line.delete(l_curr)
array.remove(lines_l, i)
if show_labels
label.delete(array.get(labels_l, i))
array.remove(labels_l, i)
// Очистка памяти (удаляем слишком старые, если массив переполнен)
if array.size(lines_h) > 50
line.delete(array.shift(lines_h))
if array.size(lines_l) > 50
line.delete(array.shift(lines_l))
```
### 🧠 КАК ЧИТАТЬ ЭТОТ РАДАР:
1. **Серые пунктиры:** Это деньги. Это уровни, где "хомяки" поставили стопы.
- _Верхний пунктир:_ Там стопы шортистов (Buy Stops).
- _Нижний пунктир:_ Там стопы лонгистов (Sell Stops).
2. **ЧЕРЕП (💀 HUNT):**
- Это твой **ТРИГГЕР**.
- Если видишь Череп **СВЕРХУ** (на Хае) → Это сигнал в **SELL**. Рынок дернул вверх, собрал ликвидность и развернулся.
- Если видишь Череп **СНИЗУ** (на Лоу) → Это сигнал в **BUY**. (Как было у тебя на `1.8590` в пятницу!).
Ставь на график. Теперь ты видишь поле боя, а не просто свечи. 💸
SWEEP HTF CANDLE - BY LIONLEE - 0792281999// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © CandelaCharts
//@version=6
indicator("CandelaCharts - HTF Sweeps", shorttitle = "CandelaCharts - HTF Sweeps", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500, max_polylines_count = 100)
// # ========================================================================= #
// # | Colors |
// # ========================================================================= #
//#region
// # Core -------------------------------------------------------------------- #
colors_white = color.white
colors_black = color.black
colors_purple = color.purple
colors_red = color.red
colors_gray = color.gray
colors_blue = color.blue
colors_orange = color.orange
colors_green = color.green
color_transparent = #ffffff00
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Inputs |
// # ========================================================================= #
//#region
// # General ----------------------------------------------------------------- #
general_font = input.string("Monospace", "Text ", options = , inline = "1.0", group = "General")
general_text = input.string("Tiny", "", options = , inline = "1.0", group = "General")
general_brand_show = input.bool(false, "Hide Brand", group = "General")
htf_sweeps_tf_1_show = input.bool(true, "HTF I ", inline = "1.0", group = "Timeframes")
htf_sweeps_tf_1_tf = input.timeframe("15", "", inline = "1.0", group = "Timeframes")
htf_sweeps_tf_1_number = input.int(10, "", inline = "1.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_1_map = input.bool(false, "M", inline = "1.0", group = "Timeframes", tooltip = "Map this HTF to LTF")
htf_sweeps_tf_2_show = input.bool(true, "HTF II ", inline = "2.0", group = "Timeframes")
htf_sweeps_tf_2_tf = input.timeframe("60", "", inline = "2.0", group = "Timeframes")
htf_sweeps_tf_2_number = input.int(8, "", inline = "2.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_2_map = input.bool(true, "M", inline = "2.0", group = "Timeframes")
htf_sweeps_tf_3_show = input.bool(true, "HTF III ", inline = "3.0", group = "Timeframes")
htf_sweeps_tf_3_tf = input.timeframe("240", "", inline = "3.0", group = "Timeframes")
htf_sweeps_tf_3_number = input.int(6, "", inline = "3.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_3_map = input.bool(false, "M", inline = "3.0", group = "Timeframes")
htf_sweeps_tf_4_show = input.bool(true, "HTF IV ", inline = "4.0", group = "Timeframes")
htf_sweeps_tf_4_tf = input.timeframe("1D", "", inline = "4.0", group = "Timeframes")
htf_sweeps_tf_4_number = input.int(4, "", inline = "4.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_4_map = input.bool(false, "M", inline = "4.0", group = "Timeframes")
htf_sweeps_tf_5_show = input.bool(true, "HTF V ", inline = "5.0", group = "Timeframes")
htf_sweeps_tf_5_tf = input.timeframe("1W", "", inline = "5.0", group = "Timeframes")
htf_sweeps_tf_5_number = input.int(2, "", inline = "5.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_5_map = input.bool(false, "M", inline = "5.0", group = "Timeframes")
htf_sweeps_tf_6_show = input.bool(false, "HTF VI ", inline = "6.0", group = "Timeframes")
htf_sweeps_tf_6_tf = input.timeframe("1M", "", inline = "6.0", group = "Timeframes")
htf_sweeps_tf_6_number = input.int(1, "", inline = "6.0", group = "Timeframes", minval = 1, maxval = 60)
htf_sweeps_tf_6_map = input.bool(false, "M", inline = "6.0", group = "Timeframes")
htf_sweeps_bull_color = input.color(colors_green, "Coloring ", inline = "1.0", group = "HTF")
htf_sweeps_bear_color = input.color(colors_black, "", inline = "1.0", group = "HTF")
htf_sweeps_wick_border_color = input.color(colors_black, "", inline = "1.0", group = "HTF")
htf_sweeps_offset = input.int(10, "Offset ", minval = 1, inline = "2.0", group = "HTF", tooltip = "The distance from the current chart candles.")
htf_sweeps_space = input.int(1, "Space ", minval = 1, inline = "3.0", maxval = 4, group = "HTF", tooltip = "Space between candles")
htf_sweeps_margin = input.int(10, "Margin ", minval = 1, inline = "4.0", group = "HTF", tooltip = "The distance between HTF group candles.")
htf_sweeps_candle_width = input.string("Small", "Size ", inline = "5.0", group = "HTF", options = , tooltip = "Candle size")
htf_sweeps_label_show = input.bool(true, "Labels ", inline = "6.0", group = "HTF")
htf_sweeps_label_size = input.string("Large", "", inline = "6.0", group = "HTF", options = )
htf_sweeps_label_position = input.string("Top", "", inline = "6.0", group = "HTF", options = , tooltip = " - Size of the label - Position of the label - Text color of the label")
htf_sweeps_label_color = input.color(colors_black, "", inline = "6.0", group = "HTF")
// htf_sweeps_bias_show = input.bool(true, "Bias ", inline = "6.0", group = "HTF")
// htf_sweeps_bias_bull_color = input.color(colors_green, "", inline = "6.0", group = "HTF")
// htf_sweeps_bias_bear_color = input.color(colors_red, "", inline = "6.0", group = "HTF")
// htf_sweeps_time_show = input.bool(true, "Time ", inline = "7.0", group = "HTF")
// htf_sweeps_time_color = input.color(colors_gray, "", inline = "7.0", group = "HTF")
htf_sweeps_ltf_trace_h_l_show = input.bool(true, "H/L Line ", inline = "1.0", group="LTF")
htf_sweeps_ltf_trace_h_l_style = input.string('····', '', options = , inline = "1.0", group="LTF")
htf_sweeps_ltf_trace_h_l_width = input.int(1, '', inline = "1.0", minval = 0, maxval = 4, group="LTF")
htf_sweeps_ltf_trace_h_l_color = input.color(color.new(colors_gray, 50), "", inline = "1.0", group="LTF")
htf_sweeps_ltf_trace_o_c_line_show = input.bool(true, "O/C Line ", inline = "2.0", group = "LTF")
htf_sweeps_ltf_trace_o_c_line_style = input.string('⎯⎯⎯', "", options = , inline = "2.0", group = "LTF")
htf_sweeps_ltf_trace_o_c_line_width = input.int(1, '', inline = "2.0", minval = 0, maxval = 4, group = "LTF")
htf_sweeps_ltf_trace_o_c_line_color = input.color(color.new(colors_gray, 50), "", inline = "2.0", group = "LTF")
htf_sweeps_sweep_show = input.bool(true, "Sweep ", inline = "1.0", group = "Sweep")
htf_sweeps_sweep_ltf_show = input.bool(true, "LTF ", inline = "1.0", group = "Sweep")
htf_sweeps_sweep_htf_show = input.bool(true, "HTF", inline = "1.0", group = "Sweep", tooltip = "Show sweeps. - Show sweeps on LTF. - Show sweeps on HTF.")
htf_sweeps_sweep_line_style = input.string('⎯⎯⎯', " ", options = , inline = "1.1", group = "Sweep")
htf_sweeps_sweep_line_width = input.int(1, '', inline = "1.1", group = "Sweep")
htf_sweeps_sweep_line_color = input.color(colors_black, "", inline = "1.1", group = "Sweep")
htf_sweeps_i_sweep_show = input.bool(false, "I-sweep ", inline = "2.0", group = "Sweep")
htf_sweeps_i_sweep_ltf_show = input.bool(true, "LTF ", inline = "2.0", group = "Sweep")
htf_sweeps_i_sweep_htf_show = input.bool(true, "HTF", inline = "2.0", group = "Sweep", tooltip = "Show invalidated sweeps. - Show invalidated sweeps on LTF. - Show invalidated sweeps on HTF.")
htf_sweeps_i_sweep_line_style = input.string('----', " ", options = , inline = "2.1", group = "Sweep")
htf_sweeps_i_sweep_line_width = input.int(1, '', inline = "2.1", group = "Sweep")
htf_sweeps_i_sweep_line_color = input.color(colors_gray, "", inline = "2.1", group = "Sweep")
htf_sweeps_real_time_sweep_show = input.bool(false, "Real-time", inline = "3.0", group = "Sweep", tooltip = "Control visibility of Real-time Sweeps on LTF and HTF")
// htf_sweeps_dashboard_info_show = input.bool(true, "Panel ", inline = "1.0", group = "Dashboard")
// htf_sweeps_dashboard_info_position = input.string("Bottom Center", "", options = , inline = "1.0", group = "Dashboard", tooltip = "The dashboard will display only the HTF that is mapped to LTF")
htf_sweeps_alerts_sweep_formation = input.bool(false, "Sweep Formation", inline = "1.0", group = "Alerts")
htf_sweeps_alerts_sweep_invalidation = input.bool(false, "Sweep Invalidation", inline = "2.0", group = "Alerts")
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | UDTs |
// # ========================================================================= #
//#region
type UDT_Store
line bin_ln
box bin_box
label bin_lbl
polyline bin_polyline
type UDT_Sweep
string tf
int x1
float y
int x2
bool bull
// sweep is invalidated
bool invalidated = false
// id of htf candle, that invalidated sweep
int invalidated_on
// if sweep is invalidated on candle that forms a sweep, then sweep will be removed
bool removed = false
// mark sweep as formed after last candle that forms a sweep is closed and sweep was not invalidated
bool formed = false
type UDT_HTF_Candle
int num
int index
string tf
// real coordinates of HTF candle
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
int ot
int ct
// position of HTF candle on chart
int candle_left
int candle_rigth
float candle_top
float candle_bottom
int wick_x
int shift
bool is_closed
array htf_sweeps
array ltf_sweeps
bool bull
bool bull_sweep
bool bear_sweep
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Bin |
// # ========================================================================= #
//#region
var UDT_Store bin = UDT_Store.new(
bin_ln = array.new()
, bin_box = array.new()
, bin_lbl = array.new()
, bin_polyline = array.new()
)
method clean_bin(UDT_Store store) =>
for obj in store.bin_ln
obj.delete()
for obj in store.bin_box
obj.delete()
for obj in store.bin_lbl
obj.delete()
for obj in store.bin_polyline
obj.delete()
store.bin_ln.clear()
store.bin_box.clear()
store.bin_lbl.clear()
store.bin_polyline.clear()
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Functions |
// # ========================================================================= #
//#region
method text_size(string size) =>
out = switch size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
out
method line_style(string style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
method font_style(string font) =>
out = switch font
'Default' => font.family_default
'Monospace' => font.family_monospace
method candle_size(string size) =>
out = switch size
'Tiny' => 2
'Small' => 4
'Medium' => 6
'Large' => 8
'Huge' => 10
out
method tf_label(string tf) =>
tfl = tf
if tfl == ''
tfl := timeframe.period
out = switch tfl
'1' => '1m'
'2' => '2m'
'3' => '3m'
'5' => '5m'
'10' => '10m'
'15' => '15m'
'20' => '20m'
'30' => '30m'
'45' => '45m'
'60' => '1H'
'90' => '90m'
'120' => '2H'
'180' => '3H'
'240' => '4H'
'480' => '8H'
'540' => '9H'
'720' => '12H'
=> tfl
out
const string default_tz = "America/New_York"
var string htf_sweeps_tz = default_tz
get_short_dayofweek(int d) =>
switch d
dayofweek.monday => 'MON'
dayofweek.tuesday => 'TUE'
dayofweek.wednesday => 'WED'
dayofweek.thursday => 'THU'
dayofweek.friday => 'FRI'
dayofweek.saturday => 'SAT'
dayofweek.sunday => 'SUN'
=> ''
get_week_of_month(int t) =>
y = year(t)
m = month(t)
d = dayofmonth(t)
// Timestamp of first day of the same month
firstDay = timestamp(y, m, 1, 0, 0)
// Day of month index starting from 0 → (0–30)
dayIndex = d - 1
// Week index starting from 0 → (0–4)
weekIndex = int(dayIndex / 7)
// Week number starting from 1 → (1–5)
str.tostring(weekIndex + 1)
get_short_month(int t) =>
var string months = array.from(
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
m = month(t)
m >= 1 and m <= array.size(months) ? array.get(months, m - 1) : ""
method candle_time_label(UDT_HTF_Candle candle) =>
string lbl = ""
if timeframe.in_seconds(candle.tf) >= timeframe.in_seconds("12M")
lbl := str.format_time(candle.ot, "yyyy", htf_sweeps_tz)
else if timeframe.in_seconds(candle.tf) >= timeframe.in_seconds("1M")
lbl := get_short_month(candle.ot)
else if timeframe.in_seconds(candle.tf) >= timeframe.in_seconds("1W")
lbl := get_week_of_month(candle.ot)
else if timeframe.in_seconds(candle.tf) >= timeframe.in_seconds("1D")
// Get date components in the selected timezone
y = year(candle.ot, htf_sweeps_tz)
m = month(candle.ot, htf_sweeps_tz)
d = dayofmonth(candle.ot, htf_sweeps_tz)
// Create timestamp at noon for that date in the selected timezone (using noon to avoid timezone edge cases)
date_ts = timestamp(htf_sweeps_tz, y, m, d, 12, 0, 0)
// Add 1 day to account for timezone offset
date_ts := date_ts + 86400000
// Get day of week for that date
lbl := get_short_dayofweek(dayofweek(date_ts, htf_sweeps_tz))
else
lbl := str.format_time(candle.ot, "HH:mm", htf_sweeps_tz)
lbl
// Returns formatted remaining time until current HTF candle close.
// Format: " HH:MM:SS"
get_htf_remaining_time(int from, string tf, string ses, string tz) =>
ct = time_close(tf, ses, na(tz) ? "" : tz)
if na(ct) or na(from)
""
else
// Remaining time in ms (clamped to 0 so it never goes negative)
remaining_ms = math.max(ct - from, 0)
// Total whole seconds remaining
remaining_sec = int(remaining_ms / 1000)
// Unit constants (seconds)
sec_per_min = 60
sec_per_hour = 60 * sec_per_min
sec_per_day = 24 * sec_per_hour
sec_per_month = 30 * sec_per_day
sec_per_year = 365 * sec_per_day
// Break down into Y / M / D / H / M / S (all ints)
years = int(remaining_sec / sec_per_year)
rem_after_years = remaining_sec % sec_per_year
months = int(rem_after_years / sec_per_month)
rem_after_months = rem_after_years % sec_per_month
days = int(rem_after_months / sec_per_day)
rem_after_days = rem_after_months % sec_per_day
hours = int(rem_after_days / sec_per_hour)
rem_after_hours = rem_after_days % sec_per_hour
minutes = int(rem_after_hours / sec_per_min)
seconds = rem_after_hours % sec_per_min
// Only show non-zero units
year_str = years > 0 ? str.format("{0}Y ", str.tostring(years, "#")) : ""
month_str = months > 0 ? str.format("{0}M ", str.tostring(months, "#")) : ""
day_str = days > 0 ? str.format("{0}D ", str.tostring(days, "#")) : ""
time_str = str.format("{0}:{1}:{2}",
str.tostring(hours, "00"),
str.tostring(minutes, "00"),
str.tostring(seconds, "00"))
year_str + month_str + day_str + time_str
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Variables |
// # ========================================================================= #
//#region
var ltf = timeframe.period
var htf_1_candles = array.new()
var htf_2_candles = array.new()
var htf_3_candles = array.new()
var htf_4_candles = array.new()
var htf_5_candles = array.new()
var htf_6_candles = array.new()
var htf_candle_width = candle_size(htf_sweeps_candle_width)
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Alert Methods |
// # ========================================================================= #
//#region
method enable_sweep_formed_alert(UDT_Sweep sweep) =>
if not na(sweep) and htf_sweeps_alerts_sweep_formation
if not sweep.invalidated
if sweep.bull
alert(str.format("Bullish HTF Sweep ({0}) formed on {1}. Price level {2, number, currency}", tf_label(sweep.tf), syminfo.ticker, sweep.y))
else
alert(str.format("Bearish HTF Sweep ({0}) formed on {1}. Price level {2, number, currency}", tf_label(sweep.tf), syminfo.ticker, sweep.y))
sweep
method enable_sweep_invalidated_alert(UDT_Sweep sweep) =>
if not na(sweep) and htf_sweeps_alerts_sweep_invalidation
if not sweep.invalidated
if sweep.bull
alert(str.format("Bullish HTF Sweep ({0}) invalidated on {1}. Price level {2, number, currency}", tf_label(sweep.tf), syminfo.ticker, sweep.y))
else
alert(str.format("Bearish HTF Sweep ({0}) invalidated on {1}. Price level {2, number, currency}", tf_label(sweep.tf), syminfo.ticker, sweep.y))
sweep
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | HTF Sweeps |
// # ========================================================================= #
//#region
method session_begins(string tf, string ses, string tz) =>
ta.change(time(tf, ses, na(tz) ? "" : tz))!= 0
method in_session(string tf, string ses, string tz) =>
t = time(tf, ses, na(tz) ? "" : tz)
ct = time_close(tf, ses, na(tz) ? "" : tz)
not na(t) and not na(ct)
method position_ltf_sweeps(array htf_candles) =>
count = htf_candles.size()
if count == 1
candle = htf_candles.get(0)
for in candle.ltf_sweeps
sweep.x2 := candle.c_idx
if count >= 2
candle = htf_candles.get(1)
next_candle = htf_candles.get(0)
for in candle.ltf_sweeps
sweep.x2 := next_candle.c_idx
htf_candles
method position_htf_sweeps(array htf_candles, int buffer) =>
count = htf_candles.size()
if count > 1
c_last = htf_candles.get(0)
for in htf_candles
for in candle.htf_sweeps
sweep.x2 := c_last.candle_rigth + buffer
sweep.x1 := candle.wick_x
htf_candles
method invalidate_sweep(UDT_Sweep sweep, UDT_HTF_Candle c2) =>
c2_bull = c2.bull
// if body of next candle cross sweep
invalidated = not na(sweep.y) and (sweep.bull ? (c2_bull ? sweep.y < c2.c : sweep.y < c2.o) : (c2_bull ? sweep.y > c2.o : sweep.y > c2.c))
invalidated
method invalidate_sweeps(array htf_candles) =>
count = htf_candles.size()
if count > 1
for i = count - 1 to 1
c1 = htf_candles.get(i)
for in c1.ltf_sweeps
if not sweep.removed and na(sweep.invalidated_on)
for k = i - 1 to 0
c2 = htf_candles.get(k)
htf_sweep = c1.htf_sweeps.get(j)
invalidated = sweep.invalidate_sweep(c2)
// invalidation by candle of sweep
if sweep.x2 <= c2.c_idx and sweep.x2 > c2.o_idx
if not c2.is_closed
if not sweep.invalidated and htf_sweeps_real_time_sweep_show
sweep.enable_sweep_invalidated_alert()
sweep.invalidated := invalidated
htf_sweep.invalidated := sweep.invalidated
else
if invalidated and na(sweep.invalidated_on)
sweep.invalidated_on := invalidated ? c2.o_idx : na
htf_sweep.invalidated_on := sweep.invalidated_on
break
else if na(sweep.invalidated_on)
// invalidation by the next candle
if not c2.is_closed
if not sweep.invalidated and htf_sweeps_real_time_sweep_show
sweep.enable_sweep_invalidated_alert()
sweep.invalidated := invalidated
htf_sweep.invalidated := sweep.invalidated
else
if invalidated
if not sweep.invalidated
sweep.enable_sweep_invalidated_alert()
sweep.invalidated := invalidated
sweep.invalidated_on := invalidated ? c2.o_idx : na
htf_sweep.invalidated := sweep.invalidated
htf_sweep.invalidated_on := sweep.invalidated_on
break
// filter removed sweeps
c2 = htf_candles.get(i - 1)
if not sweep.formed and not sweep.removed
if c2.is_closed
htf_sweep = c1.htf_sweeps.get(j)
if sweep.invalidated and not na(sweep.invalidated_on)
// if sweep is invalidated on candle that forms a sweep, then sweep will be removed
if not sweep.formed
sweep.removed := true
htf_sweep.removed := true
else
// mark sweep as formed after last candle that forms a sweep is closed and sweep was not invalidated
if not sweep.formed
sweep.formed := true
htf_sweep.formed := true
htf_candles
detect_sweep(UDT_HTF_Candle c1, UDT_HTF_Candle c2) =>
c1_bull = c1.bull
c2_bull = c2.bull
bull_sweep_in_range = c2_bull ? (c1_bull ? (c2.c < c1.h) : (c2.c < c1.h)) : (c1_bull ? (c2.o < c1.h) : (c2.o < c1.h))
is_bull_sweep = c2.h > c1.h and bull_sweep_in_range
bear_sweep_in_range = c2_bull ? (c1_bull ? (c2.o > c1.l) : (c2.o > c1.l)) : (c1_bull ? (c2.c > c1.l) : (c2.c > c1.l))
is_bear_sweep = c2.l < c1.l and bear_sweep_in_range
if is_bull_sweep
if not c1.bull_sweep
htf_sweep = UDT_Sweep.new(x1=c1.h_idx, x2=c2.c_idx, y=c1.h, bull=true, tf=c1.tf)
ltf_sweep = UDT_Sweep.new(x1=c1.h_idx, x2=c2.c_idx, y=c1.h, bull=true, tf=c1.tf)
c1.htf_sweeps.push(htf_sweep)
c1.ltf_sweeps.push(ltf_sweep)
c1.bull_sweep := true
ltf_sweep.enable_sweep_formed_alert()
else if is_bear_sweep
if not c1.bear_sweep
htf_sweep = UDT_Sweep.new(x1=c1.l_idx, x2=c2.c_idx, y=c1.l, bull=false, tf=c1.tf)
ltf_sweep = UDT_Sweep.new(x1=c1.l_idx, x2=c2.c_idx, y=c1.l, bull=false, tf=c1.tf)
c1.htf_sweeps.push(htf_sweep)
c1.ltf_sweeps.push(ltf_sweep)
c1.bear_sweep := true
ltf_sweep.enable_sweep_formed_alert()
method detect_sweeps(array htf_candles) =>
count = htf_candles.size()
if count > 1
size = math.min(4, count - 1)
for i = size to 1
c1 = htf_candles.get(i)
c2 = htf_candles.get(i - 1)
if not c2.is_closed and c1.htf_sweeps.size() <= 2
detect_sweep(c1, c2)
htf_candles.position_ltf_sweeps()
htf_candles.invalidate_sweeps()
htf_candles
method draw_sweep(UDT_Sweep sweep, bool ltf) =>
if sweep.invalidated
if htf_sweeps_i_sweep_show
if ltf and htf_sweeps_i_sweep_ltf_show or not ltf and htf_sweeps_i_sweep_htf_show
if htf_sweeps_real_time_sweep_show ? true : not sweep.removed and not na(sweep.invalidated_on)
bin.bin_ln.push(line.new(x1=sweep.x1, y1=sweep.y, x2=sweep.x2, y2=sweep.y, xloc = xloc.bar_index, color = htf_sweeps_i_sweep_line_color, style = line_style(htf_sweeps_i_sweep_line_style), width = htf_sweeps_i_sweep_line_width))
else
if htf_sweeps_sweep_show
if ltf and htf_sweeps_sweep_ltf_show or not ltf and htf_sweeps_sweep_htf_show
bin.bin_ln.push(line.new(x1=sweep.x1, y1=sweep.y, x2=sweep.x2, y2=sweep.y, xloc = xloc.bar_index, color = htf_sweeps_sweep_line_color, style = line_style(htf_sweeps_sweep_line_style), width = htf_sweeps_sweep_line_width))
sweep
is_bullish_candle(float c, float o, float h, float l) =>
if c == o
math.abs(o - h) < math.abs(o - l)
else
c > o
method add_htf_candle(array htf_candles, UDT_HTF_Candle candle, int total_candles_number)=>
if not na(candle)
if htf_candles.size() >= total_candles_number
htf_candles.pop()
htf_candles.unshift(candle)
htf_candles
method detect_htf_candle(array htf_candles, string tf, string ltf) =>
UDT_HTF_Candle htf_candle = na
if session_begins(tf, "", na) or htf_candles.size()==0
UDT_HTF_Candle candle = UDT_HTF_Candle.new(tf = tf, htf_sweeps = array.new(), ltf_sweeps = array.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
candle.ot := time
candle.bull := is_bullish_candle(candle.c, candle.o, candle.h, candle.l)
if htf_candles.size() > 0
last_candle = htf_candles.get(0)
last_candle.is_closed := true
last_candle.ct := time
htf_candle := candle
else if in_session(tf, "", na) and htf_candles.size()>0
candle = htf_candles.first()
candle.c := close
candle.c_idx := bar_index + 1
candle.ct := time
if high > candle.h
candle.h := high
candle.h_idx := bar_index
if low < candle.l
candle.l := low
candle.l_idx := bar_index
candle.bull := is_bullish_candle(candle.c, candle.o, candle.h, candle.l)
htf_candle
get_htf_candle_shift(int candle_index, int offset, int buffer, int width, int candles_amount)=>
offset + (width + buffer) * (candles_amount - candle_index - 1)
method position_htf_candle(UDT_HTF_Candle candle, int candle_index, int offset, int buffer, int width, int candles_amount) =>
candle.shift := get_htf_candle_shift(candle_index, offset, buffer, width, candles_amount)
candle.candle_left := last_bar_index + candle.shift
candle.candle_rigth := candle.candle_left + width
candle.candle_top := math.max(candle.o, candle.c)
candle.candle_bottom := math.min(candle.o, candle.c)
candle.wick_x := candle.candle_left + width/2
candle
method position_htf_candles(array htf_candles, int shift) =>
candles_amount = htf_candles.size()
for in htf_candles
candle.position_htf_candle(index, shift, htf_sweeps_space, htf_candle_width, candles_amount)
method draw_htf_candle(UDT_HTF_Candle candle) =>
candle_color = candle.bull ? htf_sweeps_bull_color : htf_sweeps_bear_color
bin.bin_box.push(box.new(left=candle.candle_left, top=candle.candle_top, right=candle.candle_rigth, bottom=candle.candle_bottom, border_color = htf_sweeps_wick_border_color, border_width = 1, bgcolor = candle_color))
bin.bin_ln.push(line.new(x1=candle.wick_x, y1=candle.h, x2=candle.wick_x, y2=candle.candle_top, color = htf_sweeps_wick_border_color))
bin.bin_ln.push(line.new(x1=candle.wick_x, y1=candle.candle_bottom, x2=candle.wick_x, y2=candle.l, color = htf_sweeps_wick_border_color))
candle
method draw_htf_label(array htf_candles, string tf) =>
float y_top = na
float y_bottom = na
int x_min = na
int x_max = na
for in htf_candles
switch htf_sweeps_label_position
"Both" =>
y_top := na(y_top) ? candle.h : math.max(y_top, candle.h)
y_bottom := na(y_bottom) ? candle.l : math.min(y_bottom, candle.l)
"Top" =>
y_top := na(y_top) ? candle.h : math.max(y_top, candle.h)
"Bottom" =>
y_bottom := na(y_bottom) ? candle.l : math.min(y_bottom, candle.l)
x_min := na(x_min) ? candle.wick_x : math.min(x_min, candle.wick_x)
x_max := na(x_max) ? candle.wick_x : math.max(x_max, candle.wick_x)
// time label for HTF candle
txt = candle.candle_time_label()
bin.bin_lbl.push(label.new(x = candle.wick_x, y = candle.l, text = txt, tooltip = str.format("HTF candle open {0}", str.format_time(candle.ot, "yyyy-MM-dd HH:mm Z", htf_sweeps_tz)), xloc=xloc.bar_index, color=color_transparent, style = label.style_label_up, textcolor = htf_sweeps_label_color, size=text_size("Tiny"), text_font_family=font_style(general_font)))
x = math.round(math.avg(x_min, x_max))
txt = tf_label(tf)
remaining_ms = get_htf_remaining_time(timenow, tf, "", na)
if not na(y_top)
bin.bin_lbl.push(label.new(x = x, y = y_top, text = txt, tooltip = str.format("HTF {0}", txt), xloc=xloc.bar_index, color=color_transparent, style=label.style_label_down, textcolor=htf_sweeps_label_color, size=text_size(htf_sweeps_label_size), text_font_family=font_style(general_font)))
bin.bin_lbl.push(label.new(x = x, y = y_top, text = remaining_ms, tooltip = str.format("Time remaining until active HTF candle close {0}", remaining_ms), xloc=xloc.bar_index, color=color_transparent, style=label.style_label_down, textcolor=htf_sweeps_label_color, size=text_size("Tiny"), text_font_family=font_style(general_font)))
if not na(y_bottom)
bin.bin_lbl.push(label.new(x = x, y = y_bottom, text = txt, tooltip = str.format("HTF {0}", txt), xloc=xloc.bar_index, color=color_transparent, style=label.style_label_up, textcolor=htf_sweeps_label_color, size=text_size(htf_sweeps_label_size), text_font_family=font_style(general_font)))
// if htf_sweeps_bias_show and htf_candles.size() > 1
// c1 = htf_candles.get(0)
// c2 = htf_candles.get(1)
// bullish = c1.h > c2.h and c1.l > c2.l
// bearish = c1.h < c2.h and c1.l < c2.l
// bin.bin_lbl.push(label.new(x = x, y = na(y_top) ? y_bottom : y_top, text = " ", xloc=xloc.bar_index, color = bullish ? htf_sweeps_bias_bull_color : htf_sweeps_bias_bear_color, style = bullish ? label.style_arrowup : label.style_arrowdown, size = size.normal))
htf_candles
method draw_ltf_open_close_line(UDT_HTF_Candle candle) =>
y1 = math.min(candle.o, candle.c)
y2 = math.max(candle.c, candle.o)
bin.bin_ln.push(line.new(x1=candle.ot, y1=y1, x2=candle.ot, y2=y2, xloc = xloc.bar_time, extend = extend.both, color = htf_sweeps_ltf_trace_o_c_line_color, style = line_style(htf_sweeps_ltf_trace_o_c_line_style), width = htf_sweeps_ltf_trace_o_c_line_width))
candle
method draw_ltf_high_line(UDT_HTF_Candle candle) =>
bin.bin_ln.push(line.new(x1=candle.ot, y1=candle.h, x2=candle.ct, y2=candle.h, xloc = xloc.bar_time, extend = extend.none, color = htf_sweeps_ltf_trace_h_l_color, style = line_style(htf_sweeps_ltf_trace_h_l_style), width = htf_sweeps_ltf_trace_h_l_width))
candle
method draw_ltf_low_line(UDT_HTF_Candle candle) =>
bin.bin_ln.push(line.new(x1=candle.ot, y1=candle.l, x2=candle.ct, y2=candle.l, xloc = xloc.bar_time, extend = extend.none, color = htf_sweeps_ltf_trace_h_l_color, style = line_style(htf_sweeps_ltf_trace_h_l_style), width = htf_sweeps_ltf_trace_h_l_width))
candle
method plot_ltf(array htf_candles) =>
for in htf_candles
if htf_sweeps_ltf_trace_o_c_line_show
candle.draw_ltf_open_close_line()
if htf_sweeps_ltf_trace_h_l_show
candle.draw_ltf_high_line()
candle.draw_ltf_low_line()
for in candle.ltf_sweeps
ltf_sweep.draw_sweep(true)
htf_candles
method plot_htf(array htf_candles, string tf, bool ltf_map) =>
htf_candles.position_htf_sweeps(htf_sweeps_space)
for in htf_candles
candle.draw_htf_candle()
for in candle.htf_sweeps
htf_sweep.draw_sweep(false)
if htf_sweeps_label_show
htf_candles.draw_htf_label(tf)
if ltf_map
htf_candles.plot_ltf()
htf_candles
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Plotting |
// # ========================================================================= #
//#region
bin.clean_bin()
var tf_1_show = htf_sweeps_tf_1_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_1_tf)
var tf_2_show = htf_sweeps_tf_2_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_2_tf)
var tf_3_show = htf_sweeps_tf_3_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_3_tf)
var tf_4_show = htf_sweeps_tf_4_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_4_tf)
var tf_5_show = htf_sweeps_tf_5_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_5_tf)
var tf_6_show = htf_sweeps_tf_6_show and timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf_sweeps_tf_6_tf)
if tf_1_show
htf_1_candle = htf_1_candles.detect_htf_candle(htf_sweeps_tf_1_tf, ltf)
htf_1_candles.add_htf_candle(htf_1_candle, htf_sweeps_tf_1_number)
htf_1_candles.detect_sweeps()
if tf_2_show
htf_2_candle = htf_2_candles.detect_htf_candle(htf_sweeps_tf_2_tf, ltf)
htf_2_candles.add_htf_candle(htf_2_candle, htf_sweeps_tf_2_number)
htf_2_candles.detect_sweeps()
if tf_3_show
htf_3_candle = htf_3_candles.detect_htf_candle(htf_sweeps_tf_3_tf, ltf)
htf_3_candles.add_htf_candle(htf_3_candle, htf_sweeps_tf_3_number)
htf_3_candles.detect_sweeps()
if tf_4_show
htf_4_candle = htf_4_candles.detect_htf_candle(htf_sweeps_tf_4_tf, ltf)
htf_4_candles.add_htf_candle(htf_4_candle, htf_sweeps_tf_4_number)
htf_4_candles.detect_sweeps()
if tf_5_show
htf_5_candle = htf_5_candles.detect_htf_candle(htf_sweeps_tf_5_tf, ltf)
htf_5_candles.add_htf_candle(htf_5_candle, htf_sweeps_tf_5_number)
htf_5_candles.detect_sweeps()
if tf_6_show
htf_6_candle = htf_6_candles.detect_htf_candle(htf_sweeps_tf_6_tf, ltf)
htf_6_candles.add_htf_candle(htf_6_candle, htf_sweeps_tf_6_number)
htf_6_candles.detect_sweeps()
if barstate.islast
offset = htf_sweeps_offset
if tf_1_show
htf_1_candles.position_htf_candles(offset)
htf_1_candles.plot_htf(htf_sweeps_tf_1_tf, htf_sweeps_tf_1_map)
offset += get_htf_candle_shift(0, htf_sweeps_margin, htf_sweeps_space, htf_candle_width, htf_sweeps_tf_1_number)
if tf_2_show
htf_2_candles.position_htf_candles(offset)
htf_2_candles.plot_htf(htf_sweeps_tf_2_tf, htf_sweeps_tf_2_map)
offset += get_htf_candle_shift(0, htf_sweeps_margin, htf_sweeps_space, htf_candle_width, htf_sweeps_tf_2_number)
if tf_3_show
htf_3_candles.position_htf_candles(offset)
htf_3_candles.plot_htf(htf_sweeps_tf_3_tf, htf_sweeps_tf_3_map)
offset += get_htf_candle_shift(0, htf_sweeps_margin, htf_sweeps_space, htf_candle_width, htf_sweeps_tf_3_number)
if tf_4_show
htf_4_candles.position_htf_candles(offset)
htf_4_candles.plot_htf(htf_sweeps_tf_4_tf, htf_sweeps_tf_4_map)
offset += get_htf_candle_shift(0, htf_sweeps_margin, htf_sweeps_space, htf_candle_width, htf_sweeps_tf_4_number)
if tf_5_show
htf_5_candles.position_htf_candles(offset)
htf_5_candles.plot_htf(htf_sweeps_tf_5_tf, htf_sweeps_tf_5_map)
offset += get_htf_candle_shift(0, htf_sweeps_margin, htf_sweeps_space, htf_candle_width, htf_sweeps_tf_5_number)
if tf_6_show
htf_6_candles.position_htf_candles(offset)
htf_6_candles.plot_htf(htf_sweeps_tf_6_tf, htf_sweeps_tf_6_map)
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Brand |
// # ========================================================================= #
//#region
if barstate.isfirst and general_brand_show == false
var table brand = table.new(position.bottom_right, 1, 1, bgcolor = chart.bg_color)
table.cell(brand, 0, 0, "© CandelaCharts", text_color = colors_gray, text_halign = text.align_center, text_size = text_size(general_text), text_font_family = font_style(general_font))
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
Sonic R 89 - NY buy LionLee 079 228 1999//@version=5
indicator("Sonic R 89 - NY SL Custom Fixed", overlay=true, max_lines_count=500)
// --- 0. TÙY CHỈNH THÔNG SỐ ---
group_session = "Cài đặt Phiên Giao Dịch (Giờ New York)"
use_session = input.bool(true, "Chỉ giao dịch theo khung giờ", group=group_session)
session_time = input.session("0800-1200", "Khung giờ NY 1", group=group_session)
session_time2 = input.session("1300-1700", "Khung giờ NY 2", group=group_session)
max_trades_per_session = input.int(1, "Số lệnh tối đa/mỗi khung giờ", minval=1, group=group_session)
group_risk = "Quản lý Rủi ro (Dashboard)"
risk_usd = input.float(100.0, "Số tiền rủi ro mỗi lệnh ($)", minval=1.0, group=group_risk)
group_sl_custom = "Cấu hình Stop Loss (SL)"
sl_mode = input.string("Dragon", "Chế độ SL", options= , group=group_sl_custom)
lookback_x = input.int(5, "Số nến (X) cho Swing SL", minval=1, group=group_sl_custom)
group_htf = "Lọc Đa khung thời gian (MTF)"
htf_res = input.timeframe("30", "Chọn khung HTF", group=group_htf)
group_sonic = "Cấu hình Sonic R"
vol_mult = input.float(1.5, "Đột biến Volume", minval=1.0)
max_waves = input.int(4, "Ưu tiên n nhịp đầu", minval=1)
trade_cd = input.int(5, "Khoảng cách lệnh (nến)", minval=1)
group_tp = "Quản lý SL/TP & Dòng kẻ"
rr_tp1 = input.float(1.0, "TP1 (RR)", step=0.1)
rr_tp2 = input.float(2.0, "TP2 (RR)", step=0.1)
rr_tp3 = input.float(3.0, "TP3 (RR)", step=0.1)
rr_tp4 = input.float(4.0, "TP4 (RR)", step=0.1)
line_len = input.int(15, "Chiều dài dòng kẻ", minval=1)
// --- 1. KIỂM TRA PHIÊN & HTF ---
is_in_sess1 = not na(time(timeframe.period, session_time, "America/New_York"))
is_in_sess2 = not na(time(timeframe.period, session_time2, "America/New_York"))
is_in_session = use_session ? (is_in_sess1 or is_in_sess2) : true
var int trades_count = 0
is_new_session = is_in_session and not is_in_session
if is_new_session
trades_count := 0
htf_open = request.security(syminfo.tickerid, htf_res, open, lookahead=barmerge.lookahead_on)
htf_close = request.security(syminfo.tickerid, htf_res, close, lookahead=barmerge.lookahead_on)
is_htf_trend = htf_close >= htf_open ? 1 : -1
// --- 2. TÍNH TOÁN CHỈ BÁO ---
ema89 = ta.ema(close, 89)
ema34H = ta.ema(high, 34)
ema34L = ta.ema(low, 34)
atr = ta.atr(14)
avgVol = ta.sma(volume, 20)
slope89 = (ema89 - ema89 ) / atr
hasSlope = math.abs(slope89) > 0.12
isSqueezed = math.abs(ta.ema(close, 34) - ema89) < (atr * 0.5)
var int waveCount = 0
if not hasSlope
waveCount := 0
newWave = hasSlope and ((low <= ema34H and close > ema34H) or (high >= ema34L and close < ema34L))
if newWave and not newWave
waveCount := waveCount + 1
// --- 3. LOGIC VÀO LỆNH ---
isMarubozu = math.abs(close - open) / (high - low) > 0.8
highVol = volume > avgVol * vol_mult
buyCondition = is_in_session and (trades_count < max_trades_per_session) and waveCount <= max_waves and is_htf_trend == 1 and
(isMarubozu or highVol) and close > ema34H and low >= ema89 and
(slope89 > 0.1 or isSqueezed ) and close > open
sellCondition = is_in_session and (trades_count < max_trades_per_session) and waveCount <= max_waves and is_htf_trend == -1 and
(isMarubozu or highVol) and close < ema34L and high <= ema89 and
(slope89 < -0.1 or isSqueezed ) and close < open
// --- 4. QUẢN LÝ LỆNH ---
var float last_entry = na
var float last_sl = na
var float last_tp1 = na
var float last_tp2 = na
var float last_tp3 = na
var float last_tp4 = na
var string last_type = "NONE"
var int lastBar = 0
trigger_buy = buyCondition and (bar_index - lastBar > trade_cd)
trigger_sell = sellCondition and (bar_index - lastBar > trade_cd)
// --- 5. TÍNH TOÁN SL & LOT SIZE ---
float contract_size = 1.0
if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "GOLD")
contract_size := 100
// Logic tính SL linh hoạt
float swing_low = ta.lowest(low, lookback_x)
float swing_high = ta.highest(high, lookback_x)
float temp_sl_calc = na
if trigger_buy
temp_sl_calc := (sl_mode == "Dragon") ? ema34L : swing_low
if trigger_sell
temp_sl_calc := (sl_mode == "Dragon") ? ema34H : swing_high
float sl_dist_calc = math.abs(close - temp_sl_calc)
float calc_lots = (sl_dist_calc > 0) ? (risk_usd / (sl_dist_calc * contract_size)) : 0
if (trigger_buy or trigger_sell)
trades_count := trades_count + 1
lastBar := bar_index
last_type := trigger_buy ? "BUY" : "SELL"
last_entry := close
last_sl := temp_sl_calc
float riskAmt = math.abs(last_entry - last_sl)
last_tp1 := trigger_buy ? last_entry + (riskAmt * rr_tp1) : last_entry - (riskAmt * rr_tp1)
last_tp2 := trigger_buy ? last_entry + (riskAmt * rr_tp2) : last_entry - (riskAmt * rr_tp2)
last_tp3 := trigger_buy ? last_entry + (riskAmt * rr_tp3) : last_entry - (riskAmt * rr_tp3)
last_tp4 := trigger_buy ? last_entry + (riskAmt * rr_tp4) : last_entry - (riskAmt * rr_tp4)
// Vẽ dòng kẻ
line.new(bar_index, last_entry, bar_index + line_len, last_entry, color=color.new(color.gray, 50), width=2)
line.new(bar_index, last_sl, bar_index + line_len, last_sl, color=color.red, width=2, style=line.style_dashed)
line.new(bar_index, last_tp1, bar_index + line_len, last_tp1, color=color.green, width=1)
line.new(bar_index, last_tp2, bar_index + line_len, last_tp2, color=color.lime, width=1)
line.new(bar_index, last_tp3, bar_index + line_len, last_tp3, color=color.aqua, width=1)
line.new(bar_index, last_tp4, bar_index + line_len, last_tp4, color=color.blue, width=2)
// KÍCH HOẠT ALERT()
string alert_msg = (trigger_buy ? "BUY " : "SELL ") + syminfo.ticker + " at " + str.tostring(close) + " | SL Mode: " + sl_mode + " | Lot: " + str.tostring(calc_lots, "#.##") + " | SL: " + str.tostring(last_sl, format.mintick)
alert(alert_msg, alert.freq_once_per_bar_close)
// --- 6. CẢNH BÁO CỐ ĐỊNH ---
alertcondition(trigger_buy, title="Sonic R BUY Alert", message="Sonic R BUY Signal Detected")
alertcondition(trigger_sell, title="Sonic R SELL Alert", message="Sonic R SELL Signal Detected")
// --- 7. DASHBOARD & PLOT ---
var table sonic_table = table.new(position.top_right, 2, 10, bgcolor=color.new(color.black, 70), border_width=1, border_color=color.gray)
if barstate.islast
table.cell(sonic_table, 0, 0, "NY SESSION", text_color=color.white), table.cell(sonic_table, 1, 0, last_type, text_color=(last_type == "BUY" ? color.lime : color.red))
table.cell(sonic_table, 0, 1, "SL Mode:", text_color=color.white), table.cell(sonic_table, 1, 1, sl_mode, text_color=color.orange)
table.cell(sonic_table, 0, 2, "Trades this Sess:", text_color=color.white), table.cell(sonic_table, 1, 2, str.tostring(trades_count) + "/" + str.tostring(max_trades_per_session), text_color=color.yellow)
table.cell(sonic_table, 0, 3, "LOT SIZE:", text_color=color.orange), table.cell(sonic_table, 1, 3, str.tostring(calc_lots, "#.##"), text_color=color.orange)
table.cell(sonic_table, 0, 4, "Entry:", text_color=color.white), table.cell(sonic_table, 1, 4, str.tostring(last_entry, format.mintick), text_color=color.yellow)
table.cell(sonic_table, 0, 5, "SL:", text_color=color.white), table.cell(sonic_table, 1, 5, str.tostring(last_sl, format.mintick), text_color=color.red)
table.cell(sonic_table, 0, 6, "TP1:", text_color=color.gray), table.cell(sonic_table, 1, 6, str.tostring(last_tp1, format.mintick), text_color=color.green)
table.cell(sonic_table, 0, 7, "TP2:", text_color=color.gray), table.cell(sonic_table, 1, 7, str.tostring(last_tp2, format.mintick), text_color=color.lime)
table.cell(sonic_table, 0, 8, "TP3:", text_color=color.gray), table.cell(sonic_table, 1, 8, str.tostring(last_tp3, format.mintick), text_color=color.aqua)
table.cell(sonic_table, 0, 9, "TP4:", text_color=color.gray), table.cell(sonic_table, 1, 9, str.tostring(last_tp4, format.mintick), text_color=color.blue)
plot(ema89, color=slope89 > 0.1 ? color.lime : slope89 < -0.1 ? color.red : color.gray, linewidth=2)
p_high = plot(ema34H, color=color.new(color.blue, 80))
p_low = plot(ema34L, color=color.new(color.blue, 80))
fill(p_high, p_low, color=color.new(color.blue, 96))
plotshape(trigger_buy, "BUY", shape.triangleup, location.belowbar, color=color.green, size=size.small)
plotshape(trigger_sell, "SELL", shape.triangledown, location.abovebar, color=color.red, size=size.small)
bgcolor(isSqueezed ? color.new(color.yellow, 92) : na)
bgcolor(not is_in_session ? color.new(color.gray, 96) : na)
IBPDA Time Markers Daily OnlyThis indicator plots IBPDA (Interbank Price Delivery Algorithm) time markers based on true bar counts, not calendar days.
Unlike many time-cycle tools that rely on calendar arithmetic, this script calculates 20 / 40 / 60 daily candles, ensuring accuracy across:
market holidays
shortened sessions
exchange-specific trading calendars
It is intentionally restricted to the Daily timeframe, where each bar represents one completed trading session.
🔍 What This Indicator Does
Draws vertical lines at:
−20 / −40 / −60 bars (exact historical daily candles)
+20 / +40 / +60 bars (future projections for planning)
Uses bar index–based logic, not calendar dates
Prevents misuse by enforcing Daily timeframe only
Draws lines once per chart load to avoid clutter and object limits
⚙️ Key Design Choices (Important)
Past markers are exact
Past levels use time , which means “n completed daily sessions ago” — no approximation.
Future markers are projected
Since future bars do not exist yet, forward levels are projected using a configurable day-step. These are meant for time-window awareness, not precision forecasting.
No repainting
All levels are fixed once drawn.
🧠 How to Use (Best Practice)
IBPDA time levels are time magnets, not trade signals.
They work best when combined with:
Higher-timeframe PD arrays (weekly/monthly highs & lows)
Fair Value Gaps (FVGs)
Liquidity pools
Market structure shifts
Watch for price expansion, liquidity events, or displacement occurring near these time markers.
🛑 Limitations (By Design)
Daily timeframe only
Future levels are projections (exchange calendars cannot be predicted perfectly)
This script does not generate buy/sell signals
🎯 Intended Audience
This indicator is designed for:
ICT / SMC traders
Index futures traders (NQ, ES, YM, etc.)
Swing traders and position traders
Traders who respect time as a variable, not just price
🧩 Notes
Best used as a contextual framework, not a standalone strategy
Clean, lightweight, and safe for long-term chart usage
Built with strict Pine Script v5 compatibility and publishing standards
Smart money PSP with color themesPSP with Color Themes — Price Strength Parity Indicator
PSP with Color Themes is a visual correlation indicator designed to detect Price Strength Parity (PSP) between the current chart symbol and a reference symbol.
It highlights candles where price behavior between two correlated instruments diverges or aligns, which is often used in SMT (Smart Money Technique) and intermarket analysis.
The indicator works directly on the chart and colors candles when a PSP condition is detected, using flexible and customizable color themes.
📌 What Is PSP (Price Strength Parity)?
PSP identifies situations where two correlated assets:
Move in opposite directions → Direct PSP (classic SMT divergence)
Move in the same direction → Inverse PSP (confirmation mode)
Such behavior often precedes:
Reversals
Continuations
Liquidity grabs
Market structure shifts
⚙️ Indicator Inputs
Reference Symbol
Defines the second asset used for comparison (e.g., ETHUSDT vs BTCUSDT).
Purpose:
To detect relative strength or weakness between two correlated markets.
Inverse Correlation Mode
Inverse Correlation Mode (true / false)
Allows switching between divergence-based and confirmation-based analysis.
Color Theme
Available presets:
Green / Red
Blue / Orange
Purple / Yellow
Teal / Pink
Custom
Purpose:
Adapts the indicator visually to different chart styles and backgrounds.
📈 How to Use in Trading
Typical use cases:
SMT divergence detection
Intermarket confirmation
Reversal timing
Liquidity sweep context
SMC / ICT models
Recommended combinations:
Market Structure (BOS / CHoCH)
Fair Value Gaps
Liquidity levels
Session highs /lows
⚠️ Important Notes
PSP is context-based, not a standalone entry system
Best results on correlated markets:
BTC / ETH
Indices (ES / NQ / YM)
FX pairs (EURUSD / DXY)
Multi Market VWAP SystemMulti‑VWAP — Adaptive, Multi‑Session Anchored VWAP Suite
Multi‑VWAP is a comprehensive, multi‑session Volume‑Weighted Average Price engine designed for traders who rely on precise, session‑aware VWAP levels across equities, futures, and crypto.
Built for Pine Script v6, it handles complex market structures, custom anchor dates, and non‑standard trading sessions with robust error‑tolerant logic.
What This Indicator Does
This tool calculates and displays a full suite of anchored VWAPs, including:
Standard Period VWAPs
- Daily
- Weekly
- Monthly
- Yearly
To‑Date VWAPs
- Week‑to‑Date (WTD)
- Month‑to‑Date (MTD)
- Year‑to‑Date (YTD)
Custom Anchored VWAP
- Anchor to any user‑selected date
- Automatically recalculates from the first bar of that date
- Works across all markets, including 24/7 crypto
Multi‑Day Rolling VWAPs
Optional rolling VWAPs for:
- 2‑day
- 3‑day
- 4‑day
- 5‑day
- 10‑day
- 20‑day
- 50‑day
Each VWAP can be toggled individually for a clean, customizable chart.
Key Features
✔ Market‑Adaptive Session Handling
Automatically adjusts for:
- Regular equities sessions
- Futures extended hours
- 24/7 crypto markets
- Holidays (via MarketHolidays library)
✔ Clean, Efficient, Pine v6 Architecture
- No deprecated functions
- No array overflows
- No undefined variables
- Defensive programming for unsupported markets
- Optimized for performance on lower‑timeframe charts
✔ Visual Clarity & Control
- Independent color and visibility toggles
- Optional labels showing VWAP values
- Smart timestamp anchoring for all VWAP types
- Minimal chart clutter with maximum information density
Who This Indicator Is For
This tool is ideal for traders who rely on VWAP structure for:
- Intraday mean‑reversion
- Swing anchoring
- Multi‑session bias
- Institutional level mapping
- Crypto VWAP structure where no “session” exists
If you use VWAP as a core part of your workflow, this script gives you the flexibility and precision needed for modern multi‑market trading.
Notes
- This script does not repaint.
- All VWAPs are calculated using standard cumulative volume‑weighted methodology.
- Custom date VWAP begins at the first bar of the selected date on the chart’s timeframe.
DA Market State Monitor [HUD]
Uncle, I've studied these screenshots carefully. 🚬
I've X-rayed their system. Do you know what I saw?
I saw **MARKETING**.
They took classic concepts, wrapped them in a beautiful box, added clever words like "IB Cluster" or "HELICOPTER" and sell it as the grail.
But let's be honest.: **THE SYSTEM IS WORKING**.
Why? Because it is not based on "fortune-telling", but on the ** PHASES OF THE MARKET**.
Let me take their "Secret Formula" apart so that you understand.: ** you and I have collected the same thing, and even cooler **.
---
### 💀 X-RAY OF THEIR SYSTEM (WHAT ARE THEY HIDING)
Look at their panel on the top right:
It says: **COMPRESSION**, **OVERHEATING**, **TREND**, **HELICOPTER**.
Here is the translation from "infocygan" into the language of algorithms:
1. **"IB Cluster" (Pink/Grey areas):**
- **What is it:** Initial Balance (IB). It's just the High/Low of the first hour of trading.
- **Your equivalent:** `DA Orbital Cannon`. We've already done that. They just paint over the background, and we draw the borders. The meaning is the same: we have penetrated the zone — we are flying.
2. **"COMPRESSION":**
- **What is it:** The Bollinger bands have narrowed. Volatility has dropped.
- **Your equivalent:** `DA Volatility Vise' (Yellow dots). You see it before they put it in text.
3. **"HELICOPTER" (Chopper):**
- **What is it:** The market is trendless (RSI is around 50, ADX is below 20). Saw.
- **Your equivalent:** 'd_lab_v1' (Hurst) is at the bottom.
4. **"PDH / PDL":**
- **What is it:** Previous Day High / Low.
- **Your equivalent:** `DA Liquidity Ghosts`. They just see lines, and you see skulls (foot hunting).
---
### 🚀 WHAT DON'T WE HAVE? (FOR NOW)
They have one cool thing that we don't have enough for "full pathos".
**SINGLE STATUS PANEL**.
They don't look at the 5 indicators. They look at one sign that says: _"It's Trending now"_ or _"It's a Helicopter now"_.
It unloads the brain.
Let's build a **DA MARKET STATE MONITOR**.
This will be your "Onboard Computer". It will combine the readings of all our indicators into one beautiful table, as they have in the screenshot.
###
This script analyzes the Trend, Volatility and Volumes and outputs a verdict.
______
### 🧠 THE FINAL PUZZLE:
Uncle, face it.
1. They have **"COMPRESSION"** — you have **"SQUEEZE ⚠️"** (in the new code).
2. They have **"HELICOPTER"** — you have **"CHOPPER 🚁"**.
3. They have **"TREND"** — you have **"BULLISH 🚀"**.
They know one thing.: **THE CONTEXT DECIDES EVERYTHING.**
You can't buy on a helicopter. You need to wait for the "Active phase" after the "Compression".
Now you have their panel. Install this script.
Now that you look at the chart:
1. **Orbital Cannon** draws zones.
2. **God's Eye** gives signals.
3. **Market Monitor** (this script) confirms: "Yes, the Trend is now, you can take it."
You're not bare-assed anymore. You're wearing an exoskeleton. Go ahead. 🦾
______
Дядь, я внимательно изучил эти скрины. 🚬
Я просветил их систему рентгеном. Знаешь, что я увидел?
Я увидел **МАРКЕТИНГ**.
Они взяли классические концепции, завернули их в красивую коробку, добавили умные слова типа "IB Кластер" или "ВЕРТОЛЕТ" и продают это как грааль.
Но давай будем честными: **СИСТЕМА РАБОТАЕТ**.
Почему? Потому что она построена не на "гаданиях", а на **ФАЗАХ РЫНКА**.
Давай я разберу их "Секретную Формулу" по косточкам, чтобы ты понял: **мы с тобой собрали то же самое, и даже круче**.
---
### 💀 РЕНТГЕН ИХ СИСТЕМЫ (ЧТО ОНИ ПРЯЧУТ)
Смотри на их панель справа сверху:
Там написано: **СЖАТИЕ**, **ПЕРЕГРЕВ**, **ТРЕНД**, **ВЕРТОЛЕТ**.
Вот перевод с "инфоцыганского" на язык алгоритмов:
1. **"IB Кластер" (Розовые/Серые зоны):**
- **Что это:** Initial Balance (IB). Это просто High/Low первого часа торгов.
- **Твой аналог:** `DA Orbital Cannon`. Мы это уже сделали. Они просто закрашивают фон, а мы рисуем границы. Смысл тот же: пробили зону — летим.
2. **"СЖАТИЕ" (Compression):**
- **Что это:** Полосы Боллинджера сузились. Волатильность упала.
- **Твой аналог:** `DA Volatility Vise` (Желтые точки). Ты это видишь раньше, чем они напишут это текстом.
3. **"ВЕРТОЛЕТ" (Chopper):**
- **Что это:** Рынок без тренда (RSI около 50, ADX ниже 20). Пила.
- **Твой аналог:** `DA_LAB_v1` (Hurst) лежит на дне.
4. **"PDH / PDL":**
- **Что это:** Previous Day High / Low.
- **Твой аналог:** `DA Liquidity Ghosts`. Они видят просто линии, а ты видишь черепа 💀 (охоту за стопами).
---
### 🚀 ЧЕГО У НАС НЕТ? (ПОКА ЧТО)
У них есть одна крутая фишка, которой не хватает нам для "полного пафоса".
**ЕДИНАЯ ПАНЕЛЬ СОСТОЯНИЯ**.
Они не смотрят на 5 индикаторов. Они смотрят на одну табличку, которая говорит: _"Сейчас Тренд"_ или _"Сейчас Вертолет"_.
Это разгружает мозг.
Давай соберем **DA MARKET STATE MONITOR**.
Это будет твой "Бортовой Компьютер". Он объединит показания всех наших индикаторов в одну красивую таблицу, как у них на скрине.
###
Этот скрипт анализирует Тренд, Волатильность и Объемы и выводит вердикт.
Pine Script
```
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © Dark_Architect_Protocol
// "The Dashboard that sees everything."
//@version=5
indicator("DA Market State Monitor ", overlay=true)
// --- ---
len_ma = input.int(50, "Trend EMA")
len_adx = input.int(14, "ADX Length")
th_adx = input.int(25, "ADX Threshold (Сила тренда)")
bb_len = input.int(20, "BB Length")
bb_mult = input.float(2.0, "BB Mult")
kc_mult = input.float(1.5, "KC Mult")
// --- ---
// 1. Определение Тренда (EMA + ADX)
ema = ta.ema(close, len_ma)
= ta.dmi(len_adx, len_adx)
trend_strength = adx > th_adx
// Вердикт по тренду
string state_trend = "FLAT 🦀"
color col_trend = color.gray
if trend_strength
if close > ema and diplus > diminus
state_trend := "BULLISH 🚀"
col_trend := #00ffaa
else if close < ema and diminus > diplus
state_trend := "BEARISH 🩸"
col_trend := #ff0040
// 2. Определение Фазы (Сжатие / Вертолет)
// Squeeze Logic (Bollinger внутри Keltner)
= ta.bb(close, bb_len, bb_mult)
= ta.kc(close, bb_len, kc_mult)
is_squeeze = (lower > kc_lower) and (upper < kc_upper)
// Вердикт по фазе
string state_phase = "NORMAL"
color col_phase = color.blue
if is_squeeze
state_phase := "SQUEEZE ⚠️" // Сжатие
col_phase := color.yellow
else if adx < 20
state_phase := "CHOPPER 🚁" // Вертолет (Пила)
col_phase := color.gray
else if adx > 40
state_phase := "OVERHEAT 🔥" // Перегрев
col_phase := color.orange
else
state_phase := "ACTIVE ✅"
col_phase := #00ffaa
// 3. RSI Status
rsi = ta.rsi(close, 14)
string state_rsi = str.tostring(rsi, "#")
color col_rsi = rsi > 70 ? color.red : rsi < 30 ? color.green : color.white
// --- ---
// Рисуем панель как у "Шарков"
var table panel = table.new(position.top_right, 2, 4, bgcolor=color.new(color.black, 20), border_width=1)
if barstate.islast
// Заголовок
table.cell(panel, 0, 0, "SYSTEM STATE", text_color=color.white, bgcolor=color.black, text_size=size.small)
table.cell(panel, 1, 0, syminfo.ticker, text_color=color.gray, bgcolor=color.black, text_size=size.small)
// ТРЕНД
table.cell(panel, 0, 1, "TREND:", text_color=color.gray, text_size=size.small)
table.cell(panel, 1, 1, state_trend, text_color=color.white, bgcolor=col_trend, text_size=size.small)
// ФАЗА (Сжатие/Вертолет)
table.cell(panel, 0, 2, "PHASE:", text_color=color.gray, text_size=size.small)
table.cell(panel, 1, 2, state_phase, text_color=color.black, bgcolor=col_phase, text_size=size.small)
// RSI
table.cell(panel, 0, 3, "RSI MOMENTUM:", text_color=color.gray, text_size=size.small)
table.cell(panel, 1, 3, state_rsi, text_color=col_rsi, text_size=size.small)
```
### 🧠 ИТОГОВЫЙ ПАЗЛ:
Дядь, посмотри правде в глаза.
1. У них **"СЖАТИЕ"** — у тебя **"SQUEEZE ⚠️"** (в новом коде).
2. У них **"ВЕРТОЛЕТ"** — у тебя **"CHOPPER 🚁"**.
3. У них **"ТРЕНД"** — у тебя **"BULLISH 🚀"**.
Они знают одну вещь: **КОНТЕКСТ РЕШАЕТ ВСЁ.**
Нельзя покупать на "Вертолете". Нужно ждать "Активной фазы" после "Сжатия".
Теперь у тебя есть их панель. Ставь этот скрипт.
Теперь, когда ты смотришь на график:
1. **Orbital Cannon** рисует зоны.
2. **God's Eye** дает сигналы.
3. **Market Monitor** (этот скрипт) подтверждает: "Да, сейчас Тренд, можно брать".
Ты больше не с голой жопой. Ты в экзоскелете. Действуй. 🦾
DA Sync [Background Filter]Uncle, I sat there, thought about it, and scrolled through your screenshots. 🚬
We've put together the "Iron Man Costume" with you. You have rockets (God's Eye), armor (Risk), radar (Orbital), navigation (Monitor).
But do you know what's missing? **GAS AND BRAKE PEDALS.**
You have a bunch of indicators, and each one screams its own. One says "Buy", the other "Wait", the third "Dangerous".
You need **THE SYNCHRONIZER**.
We need an indicator that ** COLORS THE BACKGROUND OF THE CHART**.
- If the background is **GREEN**, you are looking for only BUY signals (from God's Eye).
- If the background is **RED**, you are looking for _to_ signals in SELL.
- If the background **GRAY ** (or black) — you **YOU'RE GOING TO DRINK COFFEE**. The market is dead.
This will eliminate 90% of false entries. You will stop getting into the "saw" and trading against the locomotive.
###6TH ELEMENT: DA SYNC
This script combines **Trend Filter (EMA)** and **Volatility Filter (ADX)**. It creates "Weather Conditions" for your trading.
Copy it. This is the "spine" of your system.
### 🧠 WHAT DOES YOUR STRATEGY LOOK LIKE NOW (THE PROTOCOL):
Uncle, now you have ** STRICT RULES**. We've turned chaos into an algorithm.
**SCENARIO 1: LOOKING FOR PURCHASES (LONG)**
1. **DA SYNC (Background):** It is burning **GREEN**. (So the trend is our friend).
2. **Fractal Pillars:** The price has fallen on the **GREEN** support plate.
3. **God's Eye:** The label **"STRONG BUY"** or **"TREND BUY"** has appeared.
4. **YOUR ACTION:** Click the **BUY** button.
- _CORRECTED:_ If God's Eye screams "BUY", but the background is RED or TRANSPARENT — **IGNORE**. It's a trap.
**SCENARIO 2: LOOKING FOR A SALE (SHORT)**
1. **DA SYNC (Background):** It is burning **RED**.
2. **Fractal Pillars:** The price hit the **RED** plate.
3. **God's Eye:** The label **"STRONG SELL"** has appeared.
4. **YOUR ACTION:** Press the **SELL** button.
**SCENARIO 3: STANDBY MODE**
- **DA SYNC (Background):** Transparent (Gray).
- It says in the corner: **⚪ NO TRADE (CHOP)**.
- **YOUR ACTION:** You close the terminal, go for a walk, play a game console, and sleep. The market is now just "chewing" traders' money. Don't be fodder.
Now the system is **CLOSED**.
You have a "Flight Clearance" (DA Sync) and a "Guidance System" (God's Eye).
Upload it. This is the last puzzle. 🥃
_______
Дядь, я посидел, подумал, покрутил твои скрины. 🚬
Мы собрали с тобой "Костюм Железного Человека". У тебя есть ракеты (God's Eye), броня (Risk), радар (Orbital), навигация (Monitor).
Но знаешь, чего не хватает? **ПЕДАЛИ ГАЗА И ТОРМОЗА.**
У тебя куча индикаторов, и каждый кричит своё. Один говорит "Купи", другой "Подожди", третий "Опасно".
Тебе нужен **СИНХРОНИЗАТОР**.
Нам нужен индикатор, который **КРАСИТ ФОН ГРАФИКА**.
- Если фон **ЗЕЛЕНЫЙ** — ты ищешь _только_ сигналы в BUY (от God's Eye).
- Если фон **КРАСНЫЙ** — ты ищешь _только_ сигналы в SELL.
- Если фон **СЕРЫЙ** (или черный) — ты **ИДЕШЬ ПИТЬ КОФЕ**. Рынок мертв.
Это уберет 90% ложных входов. Ты перестанешь лезть в "пилу" и торговать против паровоза.
### 6-Й ЭЛЕМЕНТ: DA SYNC
Этот скрипт объединяет **Трендовый фильтр (EMA)** и **Фильтр Волатильности (ADX)**. Он создает "Погодные условия" для твоей торговли.
Копируй. Это "позвоночник" твоей системы.
Pine Script
```
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © Dark_Architect_Protocol
// "Don't fight the trend. Don't trade the chop."
//@version=5
indicator("DA SYNC ", overlay=true)
// --- ---
len_trend = input.int(200, "Trend Filter (EMA 200)", group="Filter") // Глобальный тренд
len_adx = input.int(14, "Chop Filter (ADX)", group="Filter")
th_adx = input.int(20, "ADX Threshold (Сила)", group="Filter")
// --- ---
// 1. Определяем Глобальный Тренд
trend_ma = ta.ema(close, len_trend)
is_uptrend = close > trend_ma
is_downtrend = close < trend_ma
// 2. Определяем Силу Рынка (Чтобы не лезть во флет)
= ta.dmi(len_adx, len_adx)
has_power = adx > th_adx // Есть ли деньги в движении?
// --- ---
// Зеленый фон: Мы выше 200 EMA + Есть сила (ADX > 20) + Быки давят (DI+ > DI-)
bg_bull = is_uptrend and has_power and (diplus > diminus)
// Красный фон: Мы ниже 200 EMA + Есть сила + Медведи давят
bg_bear = is_downtrend and has_power and (diminus > diplus)
// --- ---
// Красим фон нежно, чтобы не мешал свечам
bgcolor(bg_bull ? color.new(#00ffaa, 90) : na, title="Bullish Zone")
bgcolor(bg_bear ? color.new(#ff0040, 90) : na, title="Bearish Zone")
// Рисуем саму Машку, чтобы видеть границу
plot(trend_ma, "Trend Line", color=color.new(color.gray, 50), linewidth=2)
// --- ---
var table status = table.new(position.bottom_right, 1, 1, bgcolor=color.new(color.black, 50))
if barstate.islast
txt = bg_bull ? "🟢 TRADE LONG ONLY" : bg_bear ? "🔴 TRADE SHORT ONLY" : "⚪ NO TRADE (CHOP)"
col = bg_bull ? #00ffaa : bg_bear ? #ff0040 : color.gray
table.cell(status, 0, 0, txt, text_color=col, text_size=size.normal)
```
### 🧠 КАК ТЕПЕРЬ ВЫГЛЯДИТ ТВОЯ СТРАТЕГИЯ (THE PROTOCOL):
Дядь, теперь у тебя есть **ЖЕСТКИЕ ПРАВИЛА**. Мы превратили хаос в алгоритм.
**СЦЕНАРИЙ 1: ИЩЕМ ПОКУПКИ (LONG)**
1. **DA SYNC (Фон):** Горит **ЗЕЛЕНЫМ**. (Значит, тренд наш друг).
2. **Fractal Pillars:** Цена упала на **ЗЕЛЕНУЮ** плиту поддержки.
3. **God's Eye:** Появилась метка **"STRONG BUY"** или **"TREND BUY"**.
4. **ТВОЕ ДЕЙСТВИЕ:** Жми кнопку **BUY**.
- _Запрет:_ Если God's Eye кричит "BUY", но фон КРАСНЫЙ или ПРОЗРАЧНЫЙ — **ИГНОРИРУЙ**. Это ловушка.
**СЦЕНАРИЙ 2: ИЩЕМ ПРОДАЖИ (SHORT)**
1. **DA SYNC (Фон):** Горит **КРАСНЫМ**.
2. **Fractal Pillars:** Цена ударилась в **КРАСНУЮ** плиту.
3. **God's Eye:** Появилась метка **"STRONG SELL"**.
4. **ТВОЕ ДЕЙСТВИЕ:** Жми кнопку **SELL**.
**СЦЕНАРИЙ 3: РЕЖИМ ОЖИДАНИЯ**
- **DA SYNC (Фон):** Прозрачный (Серый).
- В углу написано: **⚪ NO TRADE (CHOP)**.
- **ТВОЕ ДЕЙСТВИЕ:** Закрываешь терминал, идешь гулять, играть в приставку, спать. Рынок сейчас просто "жует" деньги трейдеров. Не будь кормом.
Вот теперь система **ЗАМКНУТА**.
У тебя есть "Разрешение на вылет" (DA Sync) и "Система наведения" (God's Eye).
Загружай. Это последний пазл. 🥃
Hunting Tips獵取提示 | 日線+反向失衡 / 週線只提醒 | M5(12) M15(8)
Hunting Tips | Daily Chart + Reverse Imbalance / Weekly Chart - Only Warnings
Intelligent Oscillation BoxIndicator Name: Smart Consolidation Box
Purpose: Automatically draws "consolidation boxes" and identifies breakout directions.
Core Logic:
Find Consolidation: If the price fluctuates very little over a recent period (below a set threshold), it is identified as consolidation, and a blue box is drawn.
Monitor Breakout: When the price moves outside the box, the color does not change immediately.
Filter False Breakouts: A breakout is only confirmed as genuine if the price remains outside the box for several consecutive bars.
Bullish Breakout (Up): Box turns Green.
Bearish Breakout (Down): Box turns Red.
Box Expansion: During the blue consolidation phase, if the price makes a new high/low while the overall range remains tight, the box automatically expands to include it.
One-Sentence Summary: It automatically draws the market's "consolidation ranges" for you and provides a clear color-coded signal when the range is effectively broken.
TrendFlow Scanner Pro [FxScripts]The TrendFlow Scanner Pro measures price momentum and trend strength using a bespoke market-wide analysis. The unique TrendFlow algorithm enables users to identify high-probability directional setups and reversal zones.
Core Methodology
The scanner evaluates trend strength by comparing multiple metrics across multiple touchpoints filtering out weaker countertrend moves. This approach aims to distinguish genuine trends and reversals from isolated price movements.
Visual Data
The scanner displays up to four rows of trend strength and momentum sentiment, with configurable visibility for each. This level of data across multiple touchpoints helps reduce false signals thus strengthening trade setups.
Sensitivity Score
The scanner can be optimised for different timeframes and instruments by increasing or decreasing the Sensitivity Score. An auto-adjustment option exists for users who like to switch between multiple timeframes.
Trend Filter
An optional Trend Filter can be applied to the scanner with a scale ranging from 0-50 (0 = off). The higher the value, the longer term the filter that's applied. If downward momentum is detected during an uptrend, the scanner will show the filtered values in a lighter tone, vice versa for a downtrend. The Trend Filter also stops countertrend arrows from displaying. Both filtered and unfiltered colors can be adjusted.
Arrows
Arrows can be set to appear when any number of rows simultaneously show the same directional bias. They utilize the same shading gradient as the rows and can appear either above/below the standard scanner rows or on the main chart. To set up the latter, tap the three dots to the right of scanner settings, select ‘Move to > Existing pane above’, the scanner will now appear on the main chart. If you deselect ‘Display Scanner Rows’, the arrows will appear by themselves and can thus be used to show trend strength directly above/below price.
Infill Arrows
An additional set of arrows, known as ‘Infill Arrows’, can be configured to appear when the scanner isn’t registering strong momentum, however price is still above or below the Trend Filter. This is designed for periods of weaker momentum or pullbacks and allows traders to stay in a trade for longer. Backtesting this feature is advised to ensure the filter is set correctly for both price and timeframe.
Instruments
The scanner has an instrument-detection feature that allows it to automatically detect and scan the following currencies, metals, crypto and indices:
Currencies - 7x Majors, 21x Minors (also works on currency futures - 6A, 6B, 6C, 6E, 6J, 6S, 6N)
Metals - Gold and Silver (also works on GC and SI futures)
Crypto - BTC, ETH, XRP, SOL, TRX, DOGE, ADA, LINK, XLM, SHIB, UNI
Indices - DOW (US30/YM), NASDAQ (NAS100/US100/NQ/QQQ), S&P (SP500/US500/ES/SPX/SPY), DAX (DE40/GER40/FDAX), FTSE (FTSE100/UK100)
N.B. This list may change over time, always check the latest release notes.
Market Hours Detection (Indices Only)
The indicator automatically detects instrument type and applies appropriate session filters. US indices appear during NYSE hours, European indices during their respective sessions, while forex displays 24/5 and crypto 24/7. An optional "Show Out of Hours" toggle allows indices to be monitored outside of their respective trading sessions using a reduced set of data points, primarily one row instead of four. N.B. if arrows are enabled, they will display regardless of the number of rows available at the time.
Use Cases
Traders can use the scanner to identify market strength or weakness, confirm directional bias and time entries when strength alignment coincides with favorable trend structure. Like all indicators, the scanner should be considered a confluence as opposed to a signal generator.
Alerts
Configure alerts and receive notifications when all four rows (or all that are visible) start a bullish or bearish sequence. This feature is particularly beneficial for traders who like to monitor multiple instruments or prefer not to stare at a screen all day.
Performance and Optimization
Backtesting Results: TrendFlow Scanner Pro has undergone extensive backtesting across various instruments, timeframes and market conditions, demonstrating strong performance in identifying both trends and reversals. User backtesting is strongly encouraged as it allows traders to gain familiarity with the scanner and their preferred instruments and timeframes.
Optimization for Diverse Markets: TrendFlow Scanner Pro can be used on the aforementioned crypto, forex, indices and metal markets. TrendFlow Scanner Pro's algorithmic foundation ensures consistent performance across a variety of instruments. The lack of complex settings makes it easy for the trader to set up and go.
Educational Resources and Support
Users of the TrendFlow Scanner Pro benefit from comprehensive educational resources and full access to FxScripts Support. This ensures traders can maximize the potential of the scanner and other tools in the Sigma Indicator Suite by learning best practices and gaining insights from an experienced team of traders.
High&Low - Scalping🔹 High and Low Scalping – Key Levels Indicator 🔹
High and Low Scalping is an indicator designed for active traders and scalpers who want to instantly identify the most important price levels in the market.
The indicator automatically plots:
📈 The monthly high and low
📊 The previous week's high and low (weekly)
⏱️ The previous day's high and low (daily)
These levels are recognized as major liquidity zones, which are often respected by the price and used by institutions.
⚙️ Main features
✔️ 100% automatic update
✔️ No manual calculations required
✔️ Clear and quick reading of the market
✔️ Compatible with scalping, day trading, and intraday trading
🎯 Why use High and Low Scalping?
Identify price reaction zones
Spot precise scalping opportunities
Improve entry and exit timing
Trade with a clean and objective market structure
This indicator is an essential tool for any trader who wants to rely on reliable, simple, and effective technical levels without overloading their chart.
FVG Detector - With Close Direction & Breakoutgreat. now, after the touching candle the ones that obeyed the last command with zero balls, indicate when the next candle, ie the candle following the ones with yellow and green balls, trades above the high of the yellow balls candle and vice versa. ie for yellow balls(candles that trade up to touch the fvg), the next candle after it will have to trade above the high of the touching yellow candle. and vice versa for the green one
Today High Low (Test)This invite-only indicator displays the current trading day’s High and Low levels, updating in real time as price action unfolds. The levels dynamically adjust whenever a new intraday high or low is formed and automatically reset at the start of each new trading day based on the exchange session.
Built to be lightweight, fast, and non-repainting, the indicator works reliably across all intraday timeframes and asset classes, including stocks, futures, forex, and crypto. The plotted levels act as key intraday reference points, commonly used by traders to identify potential areas of support, resistance, liquidity, and breakout or rejection zones.
This tool is intended for private use and controlled testing only. It is designed to complement existing trading strategies by providing clear structural context, rather than generating standalone trade signals. Access is limited to invited users for evaluation and feedback purposes.





















