三维资金流向(多色版)1️⃣ Colors Correspond to Capital Flow
Based on your multi-color logic:
Green bars → BTC-only inflow
Blue bars → Major altcoins-only inflow
Yellow bars → BTC + major altcoins inflow simultaneously
Red bars → USDT inflow (risk-off / capital retreat)
On the chart, you can observe:
Red bars densely appearing → BTC and alt prices often consolidate or decline, indicating market funds are retreating to safety.
Green bars concentrated → BTC is generally in an uptrend, indicating capital is mainly flowing into BTC.
Blue bars appearing → Major altcoins may rise while BTC is flat, showing that altcoins are absorbing funds.
Yellow bars appearing → BTC and altcoins rise together, usually signaling an overall bullish market.
2️⃣ Observed Patterns
Capital flow vs price movement:
Green + Yellow bars concentrated → BTC shows clear upward movement
Blue bars concentrated → Altcoins rise noticeably
Red bars → Both BTC and altcoins may decline or consolidate
Capital rotation phenomenon:
Red → Green → Yellow → Blue → Can be seen as a rotation of USDT → BTC → BTC+Alt → Alt
This indicates that at different stages, the market rotates between risk-off, major assets, and altcoins.
Volatility:
Tall, frequently alternating bars → Market volatility is high
Short bars → Capital flow is weak, market tends to move sideways
Cari dalam skrip untuk "bar"
Daytrade Forex Scalper TwinPulse Auction Timer IndicatorWhat this indicator is 
TwinPulse Auction Timer is a multi component execution aid designed for liquid markets. It looks for two families of opportunities
Breakouts that leave a compression area after a fresh sweep
Reversals that trigger after a sweep with strong wick polarity
It does not try to predict future prices. It measures present auction conditions with transparent rules and shows you when those conditions align. You get a simple table that says LONG SHORT or WAIT, optional session shading, clean entry and exit level visuals, and alerts you can wire to your workflow.
 Why it is different 
Most tools show a single signal. TwinPulse combines several independent signals into an Edge Score that you can tune. The components are
• Pulse. A signed measure of wick asymmetry with candle body direction
• Compression. Current true range compared with an average range
• Sweep timer. Bars elapsed since the most recent sweep of a prior high or low
• Bias. Direction of a higher timeframe candle
• Regime. Efficiency ratio and the relation of micro to macro volatility
• Location. Distance from the daily anchored VWAP
• Session. London and New York filter by time windows
Each component is visible in the inputs and in the table so you can understand why a suggestion appears. The script uses request.security() with lookahead off in all calls so it does not peek into the future. Shapes may move while a bar is open since price is still forming. They stop moving when the bar closes.
 What you will see on the chart 
• L and S shapes on entry bars
• An Exit shape at the price where a stop or the runner target would have been hit
• Four horizontal lines while a trade is active
Entry
Stop
TP1 at one R
TP2 at the runner target expressed in R
• Labels anchored to each line so you can instantly read Entry SL TP1 and TP2 with current values
• Optional shading during your session windows
• Optional daily VWAP line
 The table in the top right shows 
Action LONG SHORT IN LONG IN SHORT or WAIT
Session ON or OFF
Bias UP DOWN or FLAT
Pulse value
Compression value
Edge L percent and Edge S percent
 How it works in detail 
Pulse
For each bar the script measures up wick minus down wick divided by range and multiplies that by the sign of the candle body. The result is averaged with pulse_len. Positive numbers indicate aggressive buying. Negative numbers indicate aggressive selling. You control the minimum absolute value with pulse_thr.
Compression
Compression is the ratio of current range to an average range. You can choose the range basis. HL SMA uses simple high minus low smoothed by range_len. ATR uses classic True Range smoothed by atr_len. Values below comp_thr indicate a coil.
Sweeps and the timer
A sweep occurs when price trades beyond the highest high or lowest low seen in the previous sweep_len bars. A strict sweep requires a close back inside that prior range. The timer measures how many bars have elapsed since the last sweep. Breakout setups require the timer to exceed timer_thr.
Bias on a confirmation timeframe
A higher timeframe candle is read with confirm_tf. If close is above open bias is UP. If close is below open bias is DOWN. This keeps breakouts aligned with the prevailing drift.
Regime filters
Efficiency ratio measures the straight line change over the sum of absolute bar to bar changes over er_len. It rises in trendy conditions and falls in noise. Minimum efficiency is controlled by er_min.
Micro to macro volatility ratio compares a short lookback average range with a longer lookback average range using your chosen basis. For breakouts you usually want micro volatility to be near or above macro hence mvr_min. For reversals you often want micro volatility that is not overheated relative to macro hence mvr_max_rev.
VWAP distance gate
Daily anchored VWAP is rebuilt from the open of each session. The script computes the absolute distance from VWAP in units of your average range and requires that distance to exceed vwap_dist_thr when use_vwap_gate is true. This keeps entries away from the mean.
Edge Score
Each gate contributes a weight that you control. The script sums weights of the satisfied gates and divides by the sum of all weights to produce an Edge percent for long and an Edge percent for short. You can then require a minimum Edge percent using edge_min_pct. This turns the indicator into a step by step checklist that you can tune to your taste.
 Using the indicator step by step 
Choose markets and timeframes
The logic is designed for liquid instruments. Major currency pairs, index futures and cash index CFDs, and the most liquid crypto pairs work well. On intraday use one to fifteen minutes for signals and fifteen to sixty minutes for confirmation. On swing use one hour to one day for signals and one day for confirmation.
Decide on entry mode
Breakouts require a compression area and a sweep timer. Reversals require a strict sweep and a strong pulse. If you are unsure leave the default which allows both.
Pick a range basis
For FX and crypto HL SMA is often stable. For indices and single name equities with gaps ATR can adapt better. If results look too reactive increase the window. If results are too slow reduce it.
Tune regime filters
If you trade trend continuation raise er_min and mvr_min. If you trade counter rotation lower them and rely on the reversal path with the strict sweep condition.
Set the VWAP gate
Enabling it helps you avoid entries at the mean. Push the threshold higher on range bound days. Reduce it in strong trend days.
Table driven decision
Watch Action and the Edge percents. If the script says WAIT you can read Pulse and Compression to see what is missing. Often the best trades appear when both Edge percents are well separated and your session switch is ON.
Use the visuals
When a suggestion triggers you will see entry stop and targets. You can mirror the levels in your own workflow or use alerts.
Consider bar close
Signals are computed in real time. For a strict process you can wait until the bar closes to reduce noise.
 Inputs explained with quick guidance 
Setup
Signal TF chooses where the logic is computed. Leave blank to use the chart.
Confirm TF sets the higher timeframe for bias.
Session filter restricts signals to the London and New York windows you specify.
Invert flips long and short. It is useful on inverse instruments.
Logic options
Entry mode allows Breakouts Reversals or Both.
Average range basis selects HL SMA or ATR.
ATR length is used when ATR is selected.
Pulse source can be Regular OHLC or Heikin Ashi. Heikin Ashi smooths noisy series, but the script still runs on regular bars and you should publish and use it on standard candles to respect the platform guidance.
Core numeric settings
Sweep lookback controls the size of the liquidity pool targeted by the sweep condition.
Pulse window smooths the wick polarity measure.
Average range window controls your base range when you use HL SMA.
Pulse threshold sets the minimum polarity required.
Compression threshold sets the maximum current range relative to average to consider the market coiled.
Expansion timer bars sets how much time has passed since the last sweep before you allow a breakout.
Regime filters
Efficiency ratio length and minimum value keep you out of aimless drift.
Micro and Macro range lengths feed the micro to macro ratio.
Minimum micro to macro for breakouts and maximum micro to macro for reversals steer the two entry families.
VWAP gate and distance threshold keep you away from the mean.
Levels and trade management visuals
Runner target in R sets TP2 as a multiple of initial risk.
Stop distance as average range multiple sets initial risk size for the visuals.
Move stop to entry after one R touch turns on break even logic once price has traveled one risk unit.
Trail buffer as R fraction uses the last sweep as an anchor and keeps a dynamic stop at a chosen fraction of R beyond it.
Cooldown after exit prevents immediate re entries.
Edge Score
Weights for pulse compression timer bias efficiency ratio micro to macro VWAP gate and session let you align the checklist with your style.
Minimum Edge percent to suggest applies a final filter to LONG or SHORT suggestions.
UI
Table and markers switch the compact dashboard and the shapes.
TP and SL lines and labels draw and name each level.
TP1 partial label percent is printed in the TP1 label for clarity.
Session shading helps with focus.
Daily VWAP line is optional.
 Alerts 
The script provides alerts for Long Short Exit and for Edge percent crossing the threshold on either side. Use them to drive notifications or to sync with webhooks and your broker integration. Alerts trigger in real time and will repaint during a bar. For conservative use trigger on bar close.
 Recommended presets 
Intraday trend continuation
Confirm TF fifteen minutes
Entry mode Breakouts
Range basis HL SMA
Pulse threshold near 0.10
Compression threshold near 0.60
Timer around 18
Minimum efficiency ratio near 0.20
Minimum micro to macro near 1.00
VWAP gate enabled with distance near 0.35
Edge minimum 50 or higher
Intraday mean reversion at sweeps
Entry mode Reversals
Pulse source Regular OHLC
Compression threshold can be a little higher
Maximum micro to macro near 1.60
Efficiency ratio minimum lower near 0.12
VWAP gate enabled
Edge minimum 40 to 60
Swing trend continuation
Signal TF one hour
Confirm TF one day
Range basis ATR
ATR length around 14
Average range window 20 to 30
Efficiency ratio minimum near 0.18
Micro to macro windows 12 and 60
Edge minimum 50 to 70
These are starting points only. Your instrument and timeframe will require small adjustments.
 Limitations and honest warnings 
No indicator is perfect. TwinPulse will mark attractive conditions that do not always lead to profitable trades. During economic releases or very thin liquidity the assumptions behind compression and sweeps may fail. In strong gap environments the HL SMA basis may lag while ATR may overreact. Heikin Ashi pulse can help in choppy markets but it will lag during sharp reversals. Session times use the exchange time of your chart. If you switch symbol or exchange verify the windows.
Edge percent is not a probability of profit. It is the fraction of satisfied gates with your chosen weights. Two traders can set different weights and see different Edge readings on the same bar. That is the design. The score is a guide that helps you act with discipline.
This indicator does not place orders or manage real risk. The lines and labels show a model entry a model stop and two model targets built from the average range at entry and from recent swing points. Use them as references and not as hard rules. Always test on historical data and demo first. Past results do not guarantee anything in the future.
 Credits and originality 
All code in this publication is original and written for this indicator. The concept of the efficiency ratio originates from Perry Kaufman. The use of a daily anchored volume weighted average price is a standard industry tool. The specific combination of pulse from wick polarity strict sweep timing compression and the tunable Edge Score is unique to this script at the time of publication. If you reuse parts of the open source code in your own work remember to credit the author and contribute meaningful improvements.
 How to read the table at a glance 
Action reflects your current state.
IN LONG or IN SHORT appears while a trade is active.
LONG or SHORT appears when conditions for entry are met and the Edge threshold is satisfied.
WAIT appears when at least one gate is missing.
Session shows ON during your chosen windows.
Bias shows the color of the confirmation candle.
Pulse is the smoothed polarity number.
Comp shows current range divided by the average range. Values below one mean compression.
Edge L percent and Edge S percent show the long and short checklists as percents.
 Final thoughts 
Markets move because orders accumulate at certain prices and at certain times. The indicator tries to measure two things that often matter at those turning points. One is the existence of a hidden imbalance revealed by wick polarity and by sweeps of prior extremes. The other is the presence of energy stored in a coil that can release in the direction of a drift. Neither force guarantees profit. Together they can improve your selection and your timing.
Use the defaults for a few days so you learn the personality of the signals. After that adjust one group at a time. Start with the session filter and the Edge threshold. Then tune compression and the timer. Finally adjust the regime filters. Keep notes. You will learn which weights matter for your market and timeframe. The result is a process you can apply with consistency.
 Disclaimer 
This script and description are for education and analysis. They are not investment advice and they do not promise future results. Use at your own risk. Test thoroughly on historical data and in simulation before considering any live use.
MULTI-CONDITION RSI SIGNAL GENERATOR═══════════════════════════════════════════════
MULTI-CONDITION RSI SIGNAL GENERATOR
═══════════════════════════════════════════════
OVERVIEW:
This indicator generates trading signals based on Relative Strength Index (RSI) movements with multiple confirmation layers designed to filter false signals and identify high-probability reversal opportunities.
═══════════════════════════════════════════════
WHAT MAKES THIS ORIGINAL:
═══════════════════════════════════════════════
Unlike basic RSI indicators that simply plot overbought/oversold crossovers, this system combines FOUR distinct confirmation mechanisms:
1. PERSISTENCE FILTERING - Requires RSI to remain in extreme zones for a minimum duration
2. LOOKBACK VALIDATION - Verifies recent extreme zone visits before signaling
3. DIVERGENCE DETECTION - Identifies price/RSI divergence for stronger signals
4. MOMENTUM CONFIRMATION - Provides trend-continuation entries via midline crosses
This multi-layered approach significantly reduces whipsaw trades that plague simple RSI crossover systems.
═══════════════════════════════════════════════
HOW IT WORKS (TECHNICAL METHODOLOGY):
═══════════════════════════════════════════════
STEP 1: RSI CALCULATION
- Standard RSI calculation using user-defined period (default: 14)
- Monitors two extreme zones: Overbought (default: 70) and Oversold (default: 30)
STEP 2: PERSISTENCE FILTERING
The script counts how many bars RSI has spent in extreme zones within the lookback period:
- For overbought signals: Counts bars where RSI > 70
- For oversold signals: Counts bars where RSI < 30
- Signal only triggers if count >= Minimum Duration (default: 4 bars)
This filters out brief spikes that immediately reverse, focusing on sustained extreme conditions that are more likely to lead to genuine reversals.
STEP 3: LOOKBACK VALIDATION
- Checks if RSI reached extreme zones within the Lookback Bars period (default: 20)
- Uses ta.highest() and ta.lowest() functions to verify recent extremes
- Ensures we're trading reversals from meaningful extremes, not random crossovers
STEP 4: BASIC SIGNAL GENERATION
- BUY SIGNAL: RSI crosses above the oversold level (30) after meeting persistence and lookback conditions
- SELL SIGNAL: RSI crosses below the overbought level (70) after meeting persistence and lookback conditions
STEP 5: DIVERGENCE DETECTION
The script identifies two types of divergence over the Divergence Lookback period (default: 5 bars):
A) BULLISH DIVERGENCE (indicates potential upward reversal):
   - Price makes a lower low (current low < previous low)
   - RSI makes a higher low (current RSI low > previous RSI low)
   - Suggests weakening downward momentum
B) BEARISH DIVERGENCE (indicates potential downward reversal):
   - Price makes a higher high (current high > previous high)
   - RSI makes a lower high (current RSI high < previous RSI high)
   - Suggests weakening upward momentum
STEP 6: STRONG SIGNAL CONFIRMATION
- STRONG BUY: Basic buy signal + bullish divergence present
- STRONG SELL: Basic sell signal + bearish divergence present
- These represent the highest-probability setups
STEP 7: MOMENTUM SIGNALS (OPTIONAL)
- MOMENTUM BUY: RSI crosses above 50 after being oversold (trend continuation)
- MOMENTUM SELL: RSI crosses below 50 after being overbought (trend continuation)
- Smaller signals for traders who want trend-following entries
═══════════════════════════════════════════════
SIGNAL TYPES AND VISUAL INDICATORS:
═══════════════════════════════════════════════
📈 GREEN TRIANGLE (below bar) - Standard Buy Signal
   RSI crossed above oversold level with confirmation filters
📉 RED TRIANGLE (above bar) - Standard Sell Signal
   RSI crossed below overbought level with confirmation filters
🔵 BLUE TRIANGLE (below bar) - Strong Buy Signal
   Buy signal + bullish divergence (HIGHEST PRIORITY)
🟣 PURPLE TRIANGLE (above bar) - Strong Sell Signal
   Sell signal + bearish divergence (HIGHEST PRIORITY)
🟢 GREEN CIRCLE (small) - Momentum Buy
   RSI crosses above 50 after oversold conditions
🔴 RED CIRCLE (small) - Momentum Sell
   RSI crosses below 50 after overbought conditions
BACKGROUND SHADING:
- Light red background: RSI currently overbought
- Light green background: RSI currently oversold
═══════════════════════════════════════════════
PARAMETER SETTINGS:
═══════════════════════════════════════════════
1. OVERBOUGHT LEVEL (default: 70, range: 50-90)
   - Higher values = fewer but stronger overbought signals
   - Lower values = more sensitive to overbought conditions
   - Recommended: 70 for standard markets, 80 for crypto/volatile assets
2. OVERSOLD LEVEL (default: 30, range: 10-50)
   - Lower values = fewer but stronger oversold signals
   - Higher values = more sensitive to oversold conditions
   - Recommended: 30 for standard markets, 20 for crypto/volatile assets
3. RSI PERIOD (default: 14, range: 2-50)
   - Standard RSI calculation period
   - Lower = more sensitive/faster signals
   - Higher = smoother/slower signals
   - Recommended: 14 (industry standard)
4. MINIMUM DURATION (default: 4, range: 1-20)
   - Required bars in extreme zone before signal
   - Higher values = fewer signals but better quality
   - Lower values = more signals but more false positives
   - Recommended: 3-5 for day trading, 5-10 for swing trading
5. LOOKBACK BARS (default: 20, range: 5-100)
   - How far back to check for extreme zone visits
   - Should match your typical trading timeframe
   - Recommended: 20 for intraday, 50 for daily charts
6. DIVERGENCE LOOKBACK (default: 5, range: 2-20)
   - Period for comparing price/RSI highs and lows
   - Lower values = more frequent divergence signals
   - Higher values = more significant divergences
   - Recommended: 5-10 depending on timeframe
═══════════════════════════════════════════════
HOW TO USE THIS INDICATOR:
═══════════════════════════════════════════════
RECOMMENDED TRADING APPROACH:
1. PRIMARY ENTRIES: Focus on Strong Buy/Sell signals (blue/purple triangles)
   - These have the highest win rate due to divergence confirmation
   - Wait for price action confirmation (support/resistance, candlestick patterns)
2. SECONDARY ENTRIES: Regular Buy/Sell signals (green/red triangles)
   - Use these when Strong signals are infrequent
   - Require additional confirmation from other indicators or chart patterns
3. TREND CONTINUATION: Momentum signals (small circles)
   - Best used when overall trend is clear
   - Not recommended for reversal trading
4. FILTER TRADES: Use background shading as context
   - Be cautious entering longs when background is red (overbought)
   - Be cautious entering shorts when background is green (oversold)
RISK MANAGEMENT GUIDELINES:
- Never risk more than 2-5% of capital per trade
- Use stop losses below recent swing lows (buys) or above swing highs (sells)
- Target at least 1.5:1 reward-to-risk ratio
- Consider position sizing based on signal strength
TIMEFRAME RECOMMENDATIONS:
- 15min - 1hour: Day trading with adjusted parameters (lower minimum duration)
- 4hour - Daily: Swing trading with default parameters
- Weekly: Position trading with increased lookback periods
COMPLEMENTARY TOOLS:
This indicator works best when combined with:
- Support and resistance levels
- Trend indicators (moving averages, trend lines)
- Volume analysis
- Price action patterns (engulfing candles, pin bars)
═══════════════════════════════════════════════
LIMITATIONS AND CONSIDERATIONS:
═══════════════════════════════════════════════
- This is NOT a standalone trading system - requires additional analysis
- RSI-based strategies perform best in ranging/choppy markets
- May generate fewer signals in strong trending markets
- Divergence signals can be early - wait for price confirmation
- Not recommended for highly illiquid assets
- Backtest on your specific market before live trading
- No indicator is 100% accurate - always use proper risk management
═══════════════════════════════════════════════
TECHNICAL NOTES:
═══════════════════════════════════════════════
- Code is original and does not reuse external libraries
- Uses Pine Script v5 native functions only
- Alert conditions included for all signal types
- No repainting - signals appear and remain fixed
- Efficient calculation methods minimize processing load
═══════════════════════════════════════════════
ALERT SETUP:
═══════════════════════════════════════════════
Four alert conditions are available:
1. "Buy Alert" - Triggers on standard buy signals
2. "Sell Alert" - Triggers on standard sell signals
3. "Strong Buy Alert" - Triggers on divergence-confirmed buy signals
4. "Strong Sell Alert" - Triggers on divergence-confirmed sell signals
To set up alerts: Right-click chart → Add Alert → Select desired condition
═══════════════════════════════════════════════
This indicator is provided for educational and informational purposes. Always practice proper risk management and never trade with money you cannot afford to lose.
Microgaps (plots-only, 4-channel, same-day only)Purpose:
This indicator visually highlights 3-bar price gaps on your chart, showing clear visual structure for gap zones without lag or diagonal artifacts.
It draws two outer lines (top and bottom of the gap) for every valid 3-bar gap, and optionally a midline when the gap is considered “large.”
⚙️ How it works
A bull gap is detected when the current bar’s low is higher than the high from two bars ago (low > high ).
A bear gap is detected when the current bar’s high is lower than the low from two bars ago (high < low ).
The lines are centered at the middle bar of the 3-bar sequence.
Gaps are only drawn within the same trading day to avoid false overnight gaps.
To prevent overlapping artifacts, up to four concurrent gap channels can be drawn efficiently using GPU-friendly plot() lines.
🔵 Midline logic
The midline (center of the gap) is only displayed when the gap’s vertical size is “large” relative to recent volatility.
“Large” means the gap height is greater than a user-defined fraction of the average bar range over the past N bars.
Example: if the average 8-bar range = 2 points, and the threshold = 0.3, then only gaps larger than 0.6 points will show the midline.
🧩 Parameters
Setting	Description
Bull Gap Color / Width	Style of bullish gaps (top and bottom lines).
Bear Gap Color / Width	Style of bearish gaps (top and bottom lines).
Mid Gap Color / Width	Style of the optional midline (shown only when “large”).
Large Gap — Lookback (bars)	Number of bars used to calculate the average range (default: 8).
Large Gap — Size vs Avg Range	Fraction of the average range that defines a “large” gap (default: 0.5). Set lower (e.g. 0.3) to show more midlines.
💡 Tips
Set threshold lower (0.2–0.4) for more midlines, higher (0.6–1.0) to highlight only extreme gaps.
Works best on intraday timeframes (1-min to 30-min).
Fully GPU-efficient — can scroll back thousands of bars without lag.
Candle count, with simple numberWhat it does 
Counts the length of same-color candle streaks (consecutive bullish or bearish bars) and prints the running number above each bar:
e.g., “1, 2, 3…”; when color flips, it restarts at “1”.
Prime numbers (2, 3, 5, 7, 11, 13) are emphasized by rendering one size step larger and with a user-selected color.
Labels are pinned to each bar (anchored by bar index and price), so they do not drift when you pan or zoom the chart.
 How it works 
Determines candle direction: bullish if close > open, bearish if close < open.
If the current bar has the same direction as the previous bar, the counter increments; otherwise it resets to 1.
For values 2, 3, 5, 7, 11, 13 the number is highlighted (bigger + custom color).
Each number is drawn just above the bar’s High with a configurable offset.
The script does not repaint on history. During the live bar, the number updates in real time (as expected).
 Settings 
Digits size — Base text size (Tiny / Small / Normal / Large / Huge).
Prime numbers are automatically shown one step larger than the base size.
Offset above bar (ticks) — Vertical offset from the bar’s High, in instrument ticks.
Prime numbers color — Text color used specifically for prime numbers (non-prime digits are white).
 How to read & use it 
Rising momentum. Long streaks (e.g., 5–7+) suggest strong directional moves with few pullbacks.
Early pause/mean-reversion hints. After a long streak, the appearance of the opposite color (counter resets to “1”) often coincides with a pause or minor retrace.
Research & statistics. Quickly see which streak lengths are common on your market/timeframe (e.g., “How often do 3–5 bar runs occur?”).
Trade management. You can tie partial exits to specific streak lengths (2, 3, 5…) or reduce risk when the counter flips back to “1”.
 Why it’s useful 
Provides a clean, numeric view of momentum with zero smoothing or lag.
Works on any symbol and timeframe.
Prime-number emphasis makes important counts pop at a glance.
Pinned labels stay exactly above their bars, ensuring stable, readable visuals at any zoom level.
 Notes 
Doji bars (close == open) are treated as no direction and reset the streak.
This is a context tool, not a standalone buy/sell signal. Combine it with your entry/exit framework.
Very dense charts may hit platform label limits; the script raises the limit, but extremely long histories on very low timeframes can still be heavy.
Smart Money Support/Resistance — LiteSmart Money Support/Resistance — Lite 
 Overview & Methodology  
This indicator identifies support and resistance as zones derived from concentrated buying and selling pressure, rather than relying solely on traditional swing highs/lows. Its design focuses on transparency: how data is sourced, how zones are computed, and how the on‑chart display should be interpreted.
 Lower‑Timeframe (LTF) Data 
The script requests Up Volume, Down Volume, and Volume Delta from a lower timeframe to expose intrabar order‑flow structure that the chart’s native timeframe cannot show. In practical terms, this lets you see where buyers or sellers briefly dominated inside the body of a higher‑timeframe bar.
 bool   use_custom_tf_input  = input.bool(true, title="Use custom lower timeframe", tooltip="Override the automatically chosen lower timeframe for volume calculations.", group=grpVolume)
string custom_tf_input      = input. Timeframe("1", title="Lower timeframe", tooltip="Lower timeframe used for up/down volume calculations (default 5 seconds).", group=grpVolume)
import TradingView/ta/10 as tvta
resolve_lower_tf(useCustom, customTF) =>
    useCustom ? customTF :
         timeframe.isseconds  ? "1S" :
         timeframe.isintraday ? "1"  :
         timeframe.isdaily    ? "5"  : "60"
get_up_down_volume(lowerTf) =>
      = tvta.requestUpAndDownVolume(lowerTf)
     
var float upVolume    = na
var float downVolume  = na
var float deltaVolume = na
string lower_tf = resolve_lower_tf(use_custom_tf_input, custom_tf_input)
  = get_up_down_volume(lower_tf)
upVolume    := u_tmp
downVolume  := d_tmp
deltaVolume := dl_tmp 
• Data source: TradingView’s ta.requestUpAndDownVolume(lowerTf) via the official TA library.
• Plan capabilities: higher‑tier subscriptions unlock seconds‑based charts and allow more historical bars per chart. This expands both the temporal depth of LTF data and the precision of short‑horizon analysis, while base tiers provide minute‑level data suitable for day/short‑swing studies.
• Coverage clarity: a small on‑chart Coverage Panel reports the active lower timeframe, the number of bars covered, and the latest computed support/resistance ranges so you always know the bounds of valid LTF input.
  
 Core Method 
 1) Data acquisition (LTF) 
The script retrieves three series from the chosen lower timeframe:
– Up Volume (buyers)
– Down Volume (sellers)
– Delta (Up – Down)
 2) Rolling window & extrema 
Over a user‑defined lookback (Global Volume Period), the algorithm builds rolling arrays of completed bars and scans for extrema:
– Buyers_max / Buyers_min from Up Volume
– Sellers_max / Sellers_min from Down Volume
Only completed bars are considered; the current bar is excluded for stability.
 3)  Price mapping 
The extrema are mapped back to their source candles to obtain price bounds:
– For “maximum” roles the algorithm uses the relevant candle highs.
– For “minimum” roles it uses the relevant candle lows.
These pairs define candidate resistance (max‑based) and support (min‑based) zones or vice versa.
 4) Zone construction & minimum width 
To ensure practicality on all symbols, zones enforce a minimum vertical thickness of two ticks. This prevents visually invisible or overly thin ranges on instruments with tight ticks.
 5) Vertical role resolution 
When both max‑ and min‑based zones exist, the script compares their midpoints. If, due to local price structure, the min‑based zone sits above the max‑based zone, display roles are swapped so the higher zone is labeled Resistance and the lower zone Support. Colors/widths are updated accordingly to keep the visual legend consistent.
 6) Rendering & panel 
Two horizontal lines and a filled box represent each active zone. The Coverage Panel (bottom‑right by default) prints:
– Lower‑timeframe in use
– Number of bars covered by LTF data
– Current Support and Resistance ranges
If the two zones overlap, an additional “Range Market” note is shown.
 Key Inputs 
• Global Volume Period: shared lookback window for the extrema search.
• Lower timeframe: user‑selectable override of the automatically resolved lower timeframe.
• Visualization toggles: independent show/hide controls and colors for maximum (resistance) and minimum (support) zones.
• Coverage Panel: enable/disable the single‑cell table and its readout.
 Operational Notes 
• The algorithm aligns all lookups to completed bars (no peeking). Price references are shifted appropriately to avoid using the still‑forming bar in calculations.
• Second‑based lower timeframes improve granularity for scalping and very short‑term entries. Minute‑based lower timeframes provide broader coverage for intraday and short‑swing contexts.
• Use the Coverage Panel to confirm the true extent of available LTF history on your symbol/plan before drawing conclusions from very deep lookbacks.
 Visual Walkthrough 
A step‑by‑step image sequence accompanies this description. Each figure demonstrates how the indicator reads LTF volume, locates extrema, builds price‑mapped zones, and updates labels/colors when vertical order requires it.
  
 Chart Interpretation 
This chart illustrates two distinct perspectives of the Smart Money Support/Resistance — Lite indicator, each derived from different lookback horizons and lower-timeframe (LTF) resolutions.
 1- Short-term view (43 bars, 10-second LTF) 
Using the most recent 43 completed bars with 10-second intrabar data, the algorithm detects that both maximum and minimum volume extrema fall within a narrow range. The result is a clearly identified range market: resistance between 178.15–184.55 and support between 175.02–179.38.
The Coverage Panel (bottom-right) confirms the scope of valid input: the lower timeframe used, number of bars covered, and the resulting zones. This short-term scan highlights how the indicator adapts to limited data depth, flagging sideways structure where neither side dominates.
 2 - Long-term view (120 bars, 30-second LTF) 
Over a wider 120-bar lookback with higher-granularity 30-second data, broader supply and demand zones emerge.
– The long-term resistance zone captures the concentration of buyers and sellers at the upper boundary of recent price history.
– The long-term support zone anchors to the opposite side of the distribution, derived from maxima and minima of both buying and selling pressure.
These zones reflect deeper structural levels where market participants previously committed significant volume.
 Combined Perspective 
 By aligning the short-term and long-term outputs, the chart shows how the indicator distinguishes immediate consolidation (range market) from more durable support and resistance levels derived from extended history. This dual resolution approach makes clear that support and resistance are not static lines but dynamic zones, dependent on both timeframe depth and the resolution of intrabar volume data. 
STRAT 3-2-2 (30m) • Upcoming / Approach / Entry + AlertsThis indicator is built for The STRAT trading method, specifically the 3-2-2 reversal pattern. It monitors price action on the 30-minute timeframe (HTF = 30m) and visually/alert-wise highlights where a 3-2-2 setup, approach, or entry trigger occurs.
---
⚙️ How it works
1. Detects bar types:
3 (Outside Bar) = range breaks both high & low of the previous bar
2u (Up bar) = higher high, not outside
2d (Down bar) = lower low, not outside
1 (Inside bar) = fully contained within prior bar
2. Looks for 3-2-2 setups:
Bullish 3-2-2 = 3 → 2d → 2u (expect reversal UP)
Bearish 3-2-2 = 3 → 2u → 2d (expect reversal DOWN)
3. Defines trigger levels:
Bullish trigger = high of the first “2d” bar
Bearish trigger = low of the first “2u” bar
4. Signals 3 phases:
Upcoming: pattern is forming, second “2” hasn’t triggered yet
Approach: price comes within 50% (adjustable) of the trigger level
Entry: price breaks the trigger (actual reversal confirmation)
5. Visualization:
Labels above/below candles show “Approach” and “Entry”
Background or bar colors (toggle in settings) highlight Setup / Approach / Entry
Optional dotted line marks the trigger level for clarity
---
🔔 Alerts
Two alert systems are built in:
1. Safe static conditions (for normal TradingView alert setup):
APPROACH: Bullish 3-2-2 (30m)
APPROACH: Bearish 3-2-2 (30m)
ENTRY: Bullish 3-2-2 (30m)
ENTRY: Bearish 3-2-2 (30m)
2. Dynamic messages (using alert() calls with price info):
If you create an alert with “Any alert() function call”, the pop-up will include the trigger price.
---
📋 Inputs (Settings)
Signal timeframe (HTF) → default 30m
Confirm signals at HTF bar close → waits for bar close (non-repainting)
Approach = % of first '2' bar range → default 50%
Show labels → On/Off
Color candles instead of background → toggle between candle color vs. chart background
FlowScape PredictorFlowScape Predictor is a non-repainting, regime-aware entry qualifier that turns complex market context into two readiness scores (Long & Short, each 0/25/50/75/100) and clean, confirmed-bar signals. It blends three orthogonal pillars so you act only when trend energy, momentum, and location agree:
Regime (energy): ATR-normalized linear-regression slope of a smooth HMA → EMA baseline, gated by ADX to confirm when pressure is meaningful.
Momentum (push): RSI slope alignment so price has directional follow-through, not just drift.
Structure (location): proximity to pivot-confirmed swings, scaled by ATR, so “ready” appears near constructive pullbacks—not mid-trend chases.
A soft ATR cloud wraps the baseline for context. A yellow Predictive Baseline extends beyond the last bar to visualize near-term trajectory. It is visual-only: scores/alerts never use it.
What you see
Baseline line that turns green/red when regime is strong in that direction; gray when weak.
ATR cloud around the baseline (context for stretch and pullbacks).
Scores (Long & Short, 0–100 in steps of 25) and optional “L/S” icons on bar close.
Yellow Predictive Baseline that extends to the right for a few bars (visual trajectory of the smoothed baseline).
The scoring system (simple and transparent)
Each side (Long/Short) sums four binary checks, 25 points each:
Regime aligned: trendStrong is true and LR slope sign favors that side.
Momentum aligned: RSI side (>50 for Long, <50 for Short) and RSI slope confirms direction.
Baseline side: price is above (Long) / below (Short) the baseline.
Location constructive: distance from the last confirmed pivot is healthy (ATR-scaled; not overstretched).
Valid totals are 0, 25, 50, 75, 100.
Best-quality signal: 100/0 (your side/opposite) on bar close.
Good, still valid: 75/0, especially when the missing block is only “location” right as price re-engages the cloud/baseline.
Avoid: 75/25 or any opposition > 0 in a weak (gray) regime.
The Predictive (Kalman) line — what it is and isn’t
The yellow line is a visual forward extension of the smoothed baseline to help you see the current trajectory and time pullback resumptions. It does not predict price and is excluded from scores and alerts.
How it’s built (plain English):
We maintain a one-dimensional Kalman state x as a smoothed estimate of the baseline. Each bar we observe the current baseline z.
The filter adjusts its trust using the Kalman gain K = P / (P + R) and updates:
x := x + K*(z − x), then P := (1 − K)*P + Q.
Q (process noise): Higher Q → expects faster change → tracks turns quicker (less smoothing).
R (measurement noise): Higher R → trusts raw baseline less → smoother, steadier projection.
What you control:
Lead (how many bars forward to draw).
Kalman Q/R (visual smoothness vs. responsiveness).
Toggle the line on/off if you prefer a minimal chart.
Important: The predictive line extends the baseline, not price. It’s a visual timing aid—don’t automate off it.
How to use (step-by-step)
Keep the chart clean and use a standard OHLC/candlestick chart.
Read the regime: Prefer trades with green/red baseline (trendStrong = true).
Check scores on bar close:
Take Long 100 / Short 0 or Long 75 / Short 0 when the chart shows a tidy pullback re-engaging the cloud/baseline.
Mirror the logic for shorts.
Confirm location: If price is > ~1.5 ATR from its reference pivot, let it come back—avoid chasing.
Set alerts: Add an alert on Long Ready or Short Ready; these fire on closed bars only.
Risk management: Use ATR-buffered stops beyond the recent pivot; target fixed-R multiples (e.g., 1.5–3.0R). Manage the trade with the baseline/cloud if you trail.
Best-practice playbook (quick rules)
Green light: 100/0 (best) or 75/0 (good) on bar close in a colored (non-gray) regime.
Location first: Prefer entries near the baseline/cloud right after a pullback, not far above/below it.
Avoid mixed signals: Skip 75/25 and anything with opposition while the baseline is gray.
Use the yellow line with discretion: It helps you see rhythm; it’s not a signal source.
Timeframes & tuning (practical defaults)
Intraday indices/FX (5m–15m): Demand 100/0 in chop; allow 75/0 when ADX is awake and pullback is clean.
Crypto intraday (15m–1h): Prefer 100/0; 75/0 on the first pullback after a regime turn.
Swing (1h–4h/D1): 75/0 is often sufficient; 100/0 is excellent (fewer but cleaner signals).
If choppy: raise ADX threshold, raise the readiness bar (insist on 100/0), or lengthen the RSI slope window.
What makes FlowScape different
Energy-first regime filter: ATR-normalized LR slope + ADX gate yields a consistent read of trend quality across symbols and timeframes.
Location-aware entries: ATR-scaled pivot proximity discourages mid-air chases, encouraging pullback timing.
Separation of concerns: The predictive line is visual-only, while scores/alerts are confirmed on close for non-repainting behavior.
One simple score per side: A single 0–100 readiness figure is easier to tune than juggling multiple indicators.
Transparency & limitations
Scores are coarse by design (25-point blocks). They’re a gatekeeper, not a promise of outcomes.
Pivots confirm after right-side bars, so structure signals appear after swings form (non-repainting by design).
Avoid using non-standard chart types (Heikin Ashi, Renko, Range, etc.) for signals; use a clean, standard chart.
No lookahead, no higher-timeframe requests; alerts fire on closed bars only.
ds-Volume with Flags & Alerts v1.2ds-Volume with Flags & Alerts: User & Training Guide
1. Summary of Features
This indicator is a powerful, all-in-one tool designed to give you a deep and customizable view of market volume. By analyzing volume in multiple ways, it helps you spot unusual activity, confirm trends, and identify potential reversals.
How It Helps a Trader:
 Spotting Institutional Activity:  The core purpose of the Volume Flags (using either the Multiplier or Standard Deviation method) is to highlight bars with exceptionally high volume. These spikes often signal the entry or exit of large institutional players. A high-volume up-bar can confirm bullish conviction, while a high-volume down-bar can signal significant selling pressure.
 Identifying Climactic Events:  The HVE (Highest Volume Ever) and HV1 (Highest Volume - 1 Year) labels automatically pinpoint the most significant volume events on the chart. A "blow-off top" at the end of a long uptrend or a "capitulation" event at a market bottom is almost always accompanied by an HVE or HV1 bar. These are critical moments to watch for potential trend reversals.
 Gauging Buying vs. Selling Pressure:  The Up/Down Volume Ratio gives you a more nuanced view than volume alone. A ratio consistently above 1.2 suggests that buyers are more aggressive, while a ratio below 0.8 suggests sellers are in control. Watching this ratio can help you confirm the strength of a trend or spot divergences where price is rising but the ratio is falling (a potential warning sign).
 Visual Confirmation & Customization:  With options to color both the volume bars and the main price bars, you can get instant visual confirmation of these events without having to look away from the price action. The ability to toggle features on and off keeps your chart clean and focused on what matters most to you.
 Actionable Alerts:  The comprehensive alert system ensures you don't miss a key event. You can be notified of everything from a new all-time high volume bar to a subtle shift in the Up/Down Volume Ratio, allowing you to react to market changes in real-time.
2. User-Changeable Options
This indicator is highly customizable. Here is a breakdown of every setting available in the "Inputs" tab.
General Settings
MA Length: The lookback period for the simple moving average (the gray area plot) of the volume.
Volume Flags
Color Price Bars with Flags: If checked, the main price bars on your chart will be colored when a high or low volume flag condition is met.
Color Volume Bars with Flags: If checked, the volume bars in the indicator pane will be colored for flag conditions.
Flag Calculation Method: This is a crucial setting.
Multiplier (Default): Identifies high volume based on a simple multiple of the average volume (e.g., volume is 1.4x its average). It's simple and intuitive.
Standard Deviation: Identifies high volume based on how statistically unusual it is compared to its recent behavior. This method is more adaptive to changing market volatility.
Daily/Weekly Lookback (Multiplier): Sets the lookback period for calculating the average volume when using the "Multiplier" method.
Daily/Weekly High-Vol Multiplier: Sets the multiplier for a high volume event (e.g., 1.4).
STDEV Length (Daily/Weekly): Sets the lookback period for calculating the average and standard deviation when using the "Standard Deviation" method.
STDEV Threshold (Daily/Weekly): Sets the number of standard deviations above the average required to trigger a high volume flag (e.g., 2.0).
Daily/Weekly Low-Vol Multiplier: Sets the threshold for a low volume event (e.g., 0.5 means volume is less than 50% of its average). This is always based on the multiplier method.
Ratios & Stats
Up/Down Ratio Daily/Weekly Lookback: Sets the lookback period for calculating the sum of up volume and down volume for the ratio.
Ratio Calculation Method:
Close vs. Open: Defines an "up volume" bar as one where the close is higher than the open.
Close vs. Previous Close (Default): Defines an "up volume" bar as one where the close is higher than the previous bar's close. This is a common standard.
Up Ratio Arrow Threshold: If the U/D Ratio exceeds this value, a green "up" arrow will appear.
Show Up Ratio Arrow: Toggles the visibility of the green "up" arrow.
Down Ratio Arrow Threshold: If the U/D Ratio falls below this value, a red "down" arrow will appear.
Show Down Ratio Arrow: Toggles the visibility of the red "down" arrow.
[Mad]Triple Bollinger Bands ForecastTriple Bollinger Bands Forecast (BBx3+F) 
This open-source indicator is an advanced version of the classic Bollinger Bands, designed to provide a more comprehensive and forward-looking view of market volatility and potential price levels. 
It plots three distinct sets of Bollinger Bands and projects them into the future based on statistical calculations.
 How It Is Built and Key Features 
 
 Triple Bollinger Bands:  Instead of a single set of bands, this indicator plots three. All three share the same central basis line (a Simple Moving Average), but each has a different standard deviation multiplier. This creates three distinct volatility zones for analyzing price deviation from its mean.
 Multi-Timeframe (MTF) Capability:  The indicator can calculate and display Bollinger Bands from a higher timeframe (e.g., showing daily bands on a 4-hour chart). This allows for contextualizing price action within the volatility structure of a more significant trend.
(Lower HTF selection will result in script-crash!)
 Future Forecasting:  This is the indicator's main feature. It projects the calculated Bollinger Bands up to 8 bars into the future. This forecast is a recalculation of the Simple Moving Average and Standard Deviation based on a projected future source price.
 Selectable Forecast Methods:  The mathematical model for estimating the future source price can be selected:
 
 Flat:  A model that uses the most recent closing price as the price for all future bars in the calculation window.
 Linreg (Linear Regression):  A model that calculates a linear regression trend on the last few bars and projects it forward to estimate the future source price.
 
 Efficient Drawing with Polylines:  The future projections are drawn on the chart using Pine Script's polyline object. This is an efficient method that draws the forecast data only on the last bar, which avoids repainting issues.
 
 Differences from a Classical Bollinger Bands Indicator 
 
 Band Count:  A classical indicator shows one set of bands. This indicator plots  three sets  for a multi-layered view of volatility.
 Perspective:  Classical Bollinger Bands are purely historical. This indicator is both historical and  forward-looking .
 Forecasting:  The classic version has no forecasting capability. This indicator  projects the bands into the future .
 Timeframe:  The classic version works only on the current timeframe. This indicator has full  Multi-Timeframe (MTF) support .
 
 The Mathematics Behind the Future Predictions 
The core challenge in forecasting Bollinger Bands is that a future band value depends on future prices, which are unknown. This indicator solves this by simulating a future price series. Here is the step-by-step logic:
 
 Forecast the Source Price for the Next Bar 
First, the indicator estimates what the price will be on the next bar.
 
 Flat Method:  The forecasted price is the current bar's closing price.
 Price_forecast = close 
 Linreg Method:  A linear regression is calculated on the last few bars and extrapolated one step forward.
 Price_forecast = ta.linreg(close, linreglen, 1) 
 
 Calculate the Future SMA (Basis) 
To calculate the Simple Moving Average for the next bar, a new data window is simulated. This window includes the new forecasted price and drops the oldest historical price. For a 1-bar forecast, the calculation is:
 SMA_future = (Price_forecast + close  + close  + ... + close ) / length 
 Calculate the Future Standard Deviation 
Similarly, the standard deviation for the next bar is calculated over this same simulated window of prices, using the new  SMA_future  as its mean.
 
// 1. Calculate the sum of squared differences from the new mean
d_f = Price_forecast - SMA_future
d_0 = close  - SMA_future
// ... and so on for the rest of the window's prices
SumOfSquares = (d_f)^2 + (d_0)^2 + ... + (d_length-2)^2
// 2. Calculate future variance and then the standard deviation
Var_future = SumOfSquares / length
StDev_future = sqrt(Var_future)
 
 Extending the Forecast (2 to 8 Bars) 
For forecasts further into the future (e.g., 2 bars), the script uses the same single  Price_forecast  for all future steps in the calculation. For a 2-bar forecast, the simulated window effectively contains the forecasted price twice, while dropping the two oldest historical prices. This provides a statistically-grounded projection of where the Bollinger Bands are likely to form.
 
 Usage as a Forecast Extension 
This indicator's functionality is designed to be modular. It can be used in conjunction with as example  Mad Triple Bollinger Bands MTF  script to separate the rendering of historical data from the forward-looking forecast.
 Configuration for Combined Use: 
 
 Add both the Mad Triple Bollinger Bands MTF and this Triple Bollinger Bands Forecast indicator to your chart.
 Open the Settings for this indicator (BBx3+F).
 In the 'General Settings' tab, disable the  Activate Plotting  option.
 To ensure data consistency, the Bollinger Length, Multipliers, and Higher Timeframe settings should be identical across both indicators.
 
This configuration prevents the rendering of duplicate historical bands. The Mad Triple Bollinger Bands MTF script will be responsible for visualizing the historical and current bands, while this script will overlay only the forward-projected polyline data.
MirPapa_Handler_HTFLibrary   "MirPapa_Handler_HTF" 
High Time Frame Handler Library:
Provides utilities for working with High Time Frame (HTF) and chart (LTF) conversions and data retrieval.
 IsChartTFcomparisonHTF(_chartTf, _htfTf) 
  IsChartTFcomparisonHTF
@description
Determine whether the given High Time Frame (HTF) is greater than or equal to the current chart timeframe.
  Parameters:
     _chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
     _htfTf (string) : The High Time Frame string to compare (examples: "60", "1D").
@return
Returns true if HTF minutes ≥ chart minutes, false otherwise or na if conversion fails.
 GetHTFrevised(_tf, _case) 
  GetHTFrevised
@description
Retrieve a specific bar value from a Higher Time Frame (HTF) series.
Supports current and historical OHLC values, based on a case identifier.
  Parameters:
     _tf (string) : The target HTF string (examples: "60", "1D").
     _case (string) : A case string determining which OHLC value and bar offset to request:
"b"   → HTF bar_index
"o"   → HTF open
"h"   → HTF high
"l"   → HTF low
"c"   → HTF close
"o1"  → HTF open one bar ago
"h1"  → HTF high one bar ago
"l1"  → HTF low one bar ago
"c1"  → HTF close one bar ago
… up to "o5", "h5", "l5", "c5" for five bars ago.
@return
Returns the requested HTF value or na if _case does not match any condition.
 GetHTFfromLabel(_label) 
  GetHTFfromLabel
@description
Convert a Korean HTF label into a Pine Script-recognizable timeframe string.
Examples:
"5분"  → "5"
"1시간" → "60"
"일봉"  → "1D"
"주봉"  → "1W"
"월봉"  → "1M"
"연봉"  → "12M"
  Parameters:
     _label (string) : The Korean HTF label string (examples: "5분", "1시간", "일봉").
@return
Returns the Pine Script timeframe string corresponding to the label, or "1W" if no match is found.
 GetHTFoffsetToLTFoffset(_offset, _chartTf, _htfTf) 
  GetHTFoffsetToLTFoffset
@description
Adjust an HTF bar index and offset so that it aligns with the current chart’s bar index.
Useful for retrieving historical HTF data on an LTF chart.
  Parameters:
     _offset (int) : The HTF bar offset (0 means current HTF bar, 1 means one bar ago, etc.).
     _chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
     _htfTf (string) : The High Time Frame string to align (examples: "60", "1D").
@return
Returns the corresponding LTF bar index after applying HTF offset. If result is negative, returns 0.
volume profile ranking indicator📌 Introduction
This script implements a volume profile ranking indicato for TradingView. It is designed to visualize the distribution of traded volume over price levels within a defined historical window. Unlike TradingView’s built-in Volume Profile, this script gives full customization of the profile drawing logic, binning, color gradient, and the ability to anchor the profile to a specific date.
⚙️ How It Works (Logic)
1. Inputs
 ➤POC Lookback Days (lookback): Defines how many bars (days) to look back from a selected point to calculate the volume distribution.
 ➤Bin Count (bin_count): Determines how many price bins (horizontal levels) the price range will be divided into.
 ➤Use Custom Lookback Date (useCustomDate): Enables/disables manually selecting a backtest start date.
 ➤Custom Lookback Date (customDate): When enabled, the profile will calculate volume based on this date instead of the most recent bar.
2. Target Bar Determination
 ➤If a custom date is selected, the script searches for the bar closest to that date within 1000 bars.
 ➤If not, it defaults to the latest bar (bar_index).
 ➤The profile is drawn only when the current bar is close to the target bar (within ±2 bars), to avoid unnecessary recalculations and performance issues.
3. Volume Binning
 ➤The price range over the lookback window is divided into bin_count segments.
 ➤For each bar within the lookback window, its volume is added to the appropriate bin based on price.
 ➤If the price falls outside the expected range, it is clamped to the first or last bin.
4. Ranking and Sorting
 ➤A bubble sort ranks each bin by total volume.
 ➤The most active bin (POC, or Point of Control) is highlighted with a thicker bar.
5. Rendering
 ➤Horizontal bars (line.new) represent volume intensity in each price bin.
 ➤Each bar is color-coded by volume heat: more volume = more intense color.
 ➤Labels (label.new) show:
 ➤Total volume
 ➤Rank
 ➤Percentage of total volume
 ➤Price range of the bin
🧑💻 How to Use
1. Add the Script to Your Chart
 ➤Copy the code into TradingView’s Pine Script editor and add it to your chart.
2. Set Lookback Period
 ➤Default is 252 bars (about one year for daily charts), but can be changed via the input.
3. (Optional) Use Custom Date
●Toggle "Use Custom Lookback Date" to true.
 ➤Pick a date in the "Custom Lookback Date" input to anchor the profile.
4. Analyze the Volume Distribution
 ➤The longest (thickest) red/orange bar represents the Point of Control (POC) — the price with the most volume traded.
 ➤Other bars show volume distribution across price.
 ➤Labels display useful metrics to evaluate areas of high/low interest.
✅ Features
🔶 Customizable anchor point (custom date).
🔶Adjustable bin count and lookback length.
🔶 Clear visualization with heatmap coloring.
🔶 Lightweight and performance-optimized (especially with the shouldDrawProfile filter)
Enhanced Volume Profile█ OVERVIEW 
The Enhanced Volume Profile (EVP) is an indicator designed to plot a volume profile on the chart based on either the visible chart range or a fixed lookback period. The script helps analyze the distribution of volume at different price levels over time, providing insights into areas of high trading activity and potential support/resistance zones.
 █ KEY FEATURES 
 1. Visible Chart Range vs. Fixed Lookback Depth 
 
 Visible Chart Range 
   - Default analysis mode
   - Calculates profile based on visible portion of the chart
   - Dynamically updates with chart view changes
 Fixed Lookback Depth 
   - Optional alternative to visible range
   - Uses specified number of bars (10-3000)
   - Provides consistent analysis depth
   - Independent of chart view
 
 2. Custom Resolution 
 Auto-Resolution Mode 
Automatically selects timeframes based on chart's current timeframe:
 
 ≤ 1 minute: Uses 1-minute resolution
 ≤ 5 minutes: Uses 1-minute resolution
 ≤ 15 minutes: Uses 5-minute resolution
 ≤ 1 hour: Uses 5-minute resolution
 ≤ 4 hours: Uses 15-minute resolution
 ≤ 12 hours: Uses 15-minute resolution
 ≤ 1 day: Uses 1-hour resolution
 ≤ 3 days: Uses 2-hours resolution
 ≤ 1 week: Uses 4-hours resolution
 
 Custom Resolution Override 
 
 Optional override of auto-resolution system
 Provides control over data granularity
 Must be lower than or equal to chart's timeframe
 Falls back to auto-resolution if validation fails
 
 3. Volume Profile Resolution 
 
 Adjustable number of points (10-400)
 Controls profile granularity
 Higher resolution provides more detail
 Balance between precision and performance
 
 4. Point of Control (PoC) 
 
 Identifies price level with highest traded volume
 Optional display with customizable appearance
 Adjustable line thickness (1-30)
 Configurable color
 
 5. Value Area (VA) 
 
 Shows price range of majority trading volume
 Adjustable coverage (5-95%), default is 68%
 Customizable boundary lines
 Configurable lines color and thickness (1-20)
 
 █ INPUT PARAMETERS 
 Lookback Settings 
 
 Use Visible Chart Range 
   - Default: true
   - Calculates profile based on visible bars
   - Ideal for focused analysis
 Fixed Lookback Bars 
   - Range: 10-3000
   - Default: 200
   - Used when visible range is disabled
 
 Resolution Settings 
 
 Enable Custom Resolution 
   - Default: false
   - Overrides auto-resolution
 Custom Resolution 
   - Default: 1-minute
   - Changes automatically when "Enable Custom Resolution" is disabled
 
 Volume Profile Appearance 
 
 Profile Resolution 
   - Range: 10-400
   - Default: 200
   - Controls detail level
 Profile Width Scale 
   - Range: 1-50
   - Default: 15
   - Adjusts profile width
 Right Offset 
   - Range: 0-500
   - Default: 20
   - Controls spacing from price bars
 Profile Fill Color 
   - Default: #5D606B (70% transparency)
 
 Point of Control Settings 
 
 Show Point of Control 
   - Default: true
   - Toggles PoC visibility
 PoC Line Thickness 
   - Range: 1-30
   - Default: 1
 PoC Line Color 
   - Default: Red
 
 Value Area Settings 
 
 Show Value Area 
   - Default: true
   - Toggles VA lines
 Value Area Coverage 
   - Range: 5-95%
   - Default: 68%
 Value Area Line Color 
   - Default: Blue
 Value Area Line Thickness 
   - Range: 1-20
   - Default: 1
 
 █ TECHNICAL IMPLEMENTATION DETAILS 
 Exceeding Bars Management  
 
 The script dynamically adjusts the number of bars used in the volume profile calculation based on the selected timeframe and the maximum allowed bars (max_bars_back).
 If the total number of bars exceeds the predefined threshold (6000 bars), the script reduces the lookback period (lookback_bars) by trimming some of the historical data, ensuring the chart does not become overloaded with data.
 The adjustment is made based on the ratio of bars per candle (bars_per_candle), ensuring that the volume profile remains computationally efficient while maintaining its relevance.
 
 █ EXAMPLE USE CASES 
 1. Visible Range Mode 
 
 For analyzing a recent trend and focusing on only the visible part of the chart, enabling the "Use Visible Chart Range" option calculates the profile based on the current view, without considering historical data outside the visible area.
 
 2. Fixed Lookback Depth 
 
 For analyzing a specific period in the past (e.g., the last 200 bars), disabling the visible range and setting a fixed lookback depth of 200 bars ensures the profile always considers the last 200 bars, regardless of the visible range.
 
 3. Custom Resolution 
 
 If there’s a need for greater control over the timeframe used for volume profile calculations (e.g., using a 5-minute resolution on a 15-minute chart), enabling custom resolution and setting the desired timeframe provides this control.
 
 HAPPY TRADING ✌️ 
Price Imbalance as Consecutive Levels of AveragesOverview
The Price Imbalance as Consecutive Levels of Averages indicator is an advanced technical analysis tool designed to identify and visualize price imbalances in financial markets. Unlike traditional moving average (MA) indicators that update continuously with each new price bar, this indicator employs moving averages calculated over consecutive, non-overlapping historical windows. This unique approach leverages comparative historical data to provide deeper insights into trend strength and potential reversals, offering traders a more nuanced understanding of market dynamics and reducing the likelihood of false signals or fakeouts.
Key Features
    Consecutive Rolling Moving Averages: Utilizes three distinct simple moving averages (SMAs) calculated over consecutive, non-overlapping windows to capture different historical segments of price data.
    Dynamic Color-Coded Visualization: SMA lines change color and style based on the relationship between the averages, highlighting both extreme and normal market conditions.
    Median and Secondary Median Lines: Provides additional layers of price distribution insight during normal trend conditions through the plotting of primary and secondary median lines.
    Fakeout Prevention: Filters out short-term volatility and sharp price movements by requiring consistent historical alignment of multiple moving averages.
    Customizable Parameters: Offers flexibility to adjust SMA window lengths and line extensions to align with various trading strategies and timeframes.
    Real-Time Updates with Historical Context: Continuously recalculates and updates SMA lines based on comparative historical windows, ensuring that the indicator reflects both current and past market conditions.
Inputs & Settings
    Rolling Window Lengths:
        Window 1 Length (Most Recent) Bars: Number of bars used to calculate the most recent SMA. (Default: 5, Range: 2–300)
        Window 2 Length (Preceding) Bars: Number of bars for the second SMA, shifted by Window 1. (Default: 8, Range: 2–300)
        Window 3 Length (Third Rolling) Bars: Number of bars for the third SMA, shifted by the combined lengths of Window 1 and Window 2. (Default: 13, Range: 2–300)
    Horizontal Line Extension:
        Horizontal Line Extension (Bars): Determines how far each SMA line extends horizontally on the chart. (Default: 10 bars, Range: 1–100)
Functionality and Theory
1. Calculating Consecutive Simple Moving Averages (SMAs):
The indicator calculates three SMAs, each based on distinct and consecutive historical windows of price data. This approach contrasts with traditional MAs that continuously update with each new price bar, offering a static view of past trends rather than an ongoing one.
    Mean1 (SMA1): Calculated over the most recent Window 1 Length bars. Represents the short-term trend.
    Mean1=∑i=1N1CloseiN1
    Mean1=N1∑i=1N1Closei
    Where N1N1 is the length of Window 1.
    Mean2 (SMA2): Calculated over the preceding Window 2 Length bars, shifted back by Window 1 Length bars. Represents the medium-term trend.
    \text{Mean2} = \frac{\sum_{i=1}^{N_2} \text{Close}_{i + N_1}}}{N_2}
    Where N2N2 is the length of Window 2.
    Mean3 (SMA3): Calculated over the third rolling Window 3 Length bars, shifted back by the combined lengths of Window 1 and Window 2 bars. Represents the long-term trend.
    \text{Mean3} = \frac{\sum_{i=1}^{N_3} \text{Close}_{i + N_1 + N_2}}}{N_3}
    Where N3N3 is the length of Window 3.
2. Determining Market Conditions:
The relationship between the three SMAs categorizes the market condition into either extreme or normal states, enabling traders to quickly assess trend strength and potential reversals.
    Extreme Bullish:
    Mean3Mean2>Mean1
    Mean3>Mean2>Mean1
    Indicates a strong and sustained downward trend. SMA lines are colored purple and styled as dashed lines.
    Normal Bullish:
    Mean1>Mean2andnot in extreme bullish condition
    Mean1>Mean2andnot in extreme bullish condition
    Indicates a standard upward trend. SMA lines are colored green and styled as solid lines.
    Normal Bearish:
    Mean1Mean2>Mean1
        Mean3>Mean2>Mean1
        Normal Bullish:
        Mean1>Mean2andnot in Extreme Bullish
        Mean1>Mean2andnot in Extreme Bullish
        Normal Bearish:
        Mean1 Mean2 > Mean3
    Visualization: All three SMAs are displayed as gold dashed lines.
    Median Lines: Not displayed to maintain chart clarity.
    Interpretation: Indicates a strong and sustained upward trend. Traders may consider entering long positions, confident in the trend's strength without the distraction of additional lines.
2. Normal Bullish Condition:
    SMAs Alignment: Mean1 > Mean2 (not in extreme condition)
    Visualization: Mean1 and Mean2 are green solid lines; Mean3 is gray.
    Median Lines: A thin blue dotted median line is plotted between Mean1 and Mean2, with two additional thin blue dashed lines as secondary medians.
    Interpretation: Confirms an upward trend while providing deeper insights into price distribution. Traders can use the median and secondary median lines to identify optimal entry points and manage risk more effectively.
3. Extreme Bearish Condition:
    SMAs Alignment: Mean3 > Mean2 > Mean1
    Visualization: All three SMAs are displayed as purple dashed lines.
    Median Lines: Not displayed to maintain chart clarity.
    Interpretation: Indicates a strong and sustained downward trend. Traders may consider entering short positions, confident in the trend's strength without the distraction of additional lines.
4. Normal Bearish Condition:
    SMAs Alignment: Mean1 < Mean2 (not in extreme condition)
    Visualization: Mean1 and Mean2 are red solid lines; Mean3 is gray.
    Median Lines: A thin blue dotted median line is plotted between Mean1 and Mean2, with two additional thin blue dashed lines as secondary medians.
    Interpretation: Confirms a downward trend while providing deeper insights into price distribution. Traders can use the median and secondary median lines to identify optimal entry points and manage risk more effectively.
Customization and Flexibility
The Price Imbalance as Consecutive Levels of Averages indicator is highly adaptable, allowing traders to tailor it to their specific trading styles and market conditions through adjustable parameters:
    SMA Window Lengths: Modify the lengths of Window 1, Window 2, and Window 3 to capture different historical trend segments, whether focusing on short-term fluctuations or long-term movements.
    Line Extension: Adjust the horizontal extension of SMA and median lines to align with different trading horizons and chart preferences.
    Color and Style Preferences: While default colors and styles are optimized for clarity, traders can customize these elements to match their personal chart aesthetics and enhance visual differentiation.
This flexibility ensures that the indicator remains versatile and applicable across various markets, asset classes, and trading strategies, providing valuable insights tailored to individual trading needs.
Conclusion
The Price Imbalance as Consecutive Levels of Averages indicator offers a comprehensive and innovative approach to analyzing price trends and imbalances within financial markets. By utilizing three consecutive, non-overlapping SMAs and incorporating median lines during normal trend conditions, the indicator provides clear and actionable insights into trend strength and price distribution. Its unique design leverages comparative historical data, distinguishing it from traditional moving averages and enhancing its utility in identifying genuine market movements while minimizing false signals. This dynamic and customizable tool empowers traders to refine their technical analysis, optimize their trading strategies, and navigate the markets with greater confidence and precision.
Anchored Geometric Brownian Motion Projections w/EVAnchored GBM (Geometric Brownian Motion) Projections + EV & Confidence Bands
Version: Pine Script v6
Overlay: Yes
Author:  
Published On:  
Overview
The Anchored GBM Projections + EV & Confidence Bands indicator leverages the Geometric Brownian Motion (GBM) model to project future price movements based on historical data. By simulating multiple potential future price paths, it provides traders with insights into possible price trajectories, their expected values, and confidence intervals. Additionally, it offers a "Mean of EV" (EV of EV) line, representing the running average of expected values across the projection period.
Key Features
    Anchor Time Setup:
        Define a specific point in time from which the projections commence.
        By default, it uses the current bar's timestamp but can be customized.
    Projection Parameters:
        Projection Candles (Bars): Determines the number of future bars (time periods) to project.
        Number of Simulations: Specifies how many GBM paths to simulate, ensuring statistical relevance via the Central Limit Theorem (CLT).
    Display Toggles:
        Simulation Lines: Visual representation of individual GBM simulation paths.
        Expected Value (EV) Line: The average price across all simulations at each projection bar.
        Upper & Lower Confidence Bands: 95% confidence intervals indicating potential price boundaries.
        EV of EV Line: Running average of EV values, providing a smoothed central tendency across the projection period. Additionally, this line often acts as an indicator of trend direction.
    Visualization:
        Clear and distinguishable lines with customizable colors and styles.
        Overlayed on the price chart for direct comparison with actual price movements.
Mathematical Foundation
    Geometric Brownian Motion (GBM):
        Definition: GBM is a continuous-time stochastic process used to model stock prices. It assumes that the logarithm of the stock price follows a Brownian motion with drift.
        Equation:
        S(t)=S0⋅e(μ−12σ2)t+σW(t)
        S(t)=S0⋅e(μ−21σ2)t+σW(t) Where:
            S(t)S(t) = Stock price at time tt
            S0S0 = Initial stock price
            μμ = Drift coefficient (average return)
            σσ = Volatility coefficient (standard deviation of returns)
            W(t)W(t) = Wiener process (standard Brownian motion)
    Drift (μμ) and Volatility (σσ):
        Drift (μμ) represents the expected return of the stock.
        Volatility (σσ) measures the stock's price fluctuation intensity.
    Central Limit Theorem (CLT):
        Principle: With a sufficiently large number of independent simulations, the distribution of the sample mean (EV) approaches a normal distribution, regardless of the underlying distribution.
        Application: Ensures that the EV and confidence bands are statistically reliable.
    Expected Value (EV) and Confidence Bands:
        EV: The mean price across all simulations at each projection bar.
        Confidence Bands: Range within which the actual price is expected to lie with a specified probability (e.g., 95%).
    EV of EV (Mean of Sample Means):
        Definition: Represents the running average of EV values across the projection period, offering a smoothed central tendency.
Methodology
    Anchor Time Setup:
        The indicator starts projecting from a user-defined Anchor Time. If not customized, it defaults to the current bar's timestamp.
        Purpose: Allows users to analyze projections from a specific historical point or the latest market data.
    Calculating Drift and Volatility:
        Returns Calculation: Computes the logarithmic returns from the Anchor Time to the current bar.
        returns=ln(StSt−1)
        returns=ln(St−1St)
        Drift (μμ): Calculated as the simple moving average (SMA) of returns over the period since the Anchor Time.
        Volatility (σσ): Determined using the standard deviation (stdev) of returns over the same period.
    Simulation Generation:
        Number of Simulations: The user defines how many GBM paths to simulate (e.g., 30).
        Projection Candles: Determines the number of future bars to project (e.g., 12).
        Process:
            For each simulation:
                Start from the current close price.
                For each projection bar:
                    Generate a random number zz from a standard normal distribution.
                    Calculate the next price using the GBM formula:
                    St+1=St⋅e(μ−12σ2)+σz
                    St+1=St⋅e(μ−21σ2)+σz
                    Store the projected price in an array.
    Expected Value (EV) and Confidence Bands Calculation:
        EV Path: At each projection bar, compute the mean of all simulated prices.
        Variance and Standard Deviation: Calculate the variance and standard deviation of simulated prices to determine the confidence intervals.
        Confidence Bands: Using the standard normal z-score (1.96 for 95% confidence), establish upper and lower bounds:
        Upper Band=EV+z⋅σEV
        Upper Band=EV+z⋅σEV
        Lower Band=EV−z⋅σEV
        Lower Band=EV−z⋅σEV
    EV of EV (Running Average of EV Values):
        Calculation: For each projection bar, compute the average of all EV  values up to that bar.
        EV of EV =1j+1∑k=0jEV 
        EV of EV =j+11k=0∑jEV 
        Visualization: Plotted as a dynamic line reflecting the evolving average EV across the projection period.
Visualization Elements
    Simulation Lines:
        Appearance: Semi-transparent blue lines representing individual GBM simulation paths.
        Purpose: Illustrate a range of possible future price trajectories based on current drift and volatility.
    Expected Value (EV) Line:
        Appearance: Solid orange line.
        Purpose: Shows the average projected price at each future bar across all simulations.
    Confidence Bands:
        Upper Band: Dashed green line indicating the upper 95% confidence boundary.
        Lower Band: Dashed red line indicating the lower 95% confidence boundary.
        Purpose: Highlight the range within which the price is statistically expected to remain with 95% confidence.
    EV of EV Line:
        Appearance: Dashed purple line.
        Purpose: Displays the running average of EV values, providing a smoothed trend of the central tendency across the projection period. As the mean of sample means it approximates the population mean (i.e. the trend since the anchor point.)
    Current Price:
        Appearance: Semi-transparent white line.
        Purpose: Serves as a reference point for comparing actual price movements against projected paths.
Usage Instructions
    Configuring User Inputs:
        Anchor Time:
            Set to a specific timestamp to start projections from a historical point or leave it as default to use the current bar's time.
        Projection Candles (Bars):
            Define the number of future bars to project (e.g., 12). Adjust based on your trading timeframe and analysis needs.
        Number of Simulations:
            Specify the number of GBM paths to simulate (e.g., 30). Higher numbers yield more accurate EV and confidence bands but may impact performance.
        Display Toggles:
            Show Simulation Lines: Toggle to display or hide individual GBM simulation paths.
            Show Expected Value Line: Toggle to display or hide the EV path.
            Show Upper Confidence Band: Toggle to display or hide the upper confidence boundary.
            Show Lower Confidence Band: Toggle to display or hide the lower confidence boundary.
            Show EV of EV Line: Toggle to display or hide the running average of EV values.
    Managing TradingView's Object Limits:
        Understanding Limits:
            TradingView imposes a limit on the number of graphical objects (e.g., lines) that can be rendered. High values for projection candles and simulations can quickly consume these limits. TradingView appears to only allow a total of 55 candles to be projected, so if you want to see two complete lines, you would have to set the projection length to 27: since 27 * 2 = 54 and 54 < 55.
        Optimizing Performance:
            Use Toggles: Enable only the necessary visual elements. For instance, disable simulation lines and confidence bands when focusing on the EV and EV of EV lines. You can also use the maximum projection length of 55 with the lower limit confidence band as the only line, visualizing a long horizon for your risk.
            Adjust Parameters: Lower the number of projection candles or simulations to stay within object limits without compromising essential insights.
    Interpreting the Indicator:
        Simulation Lines (Blue):
            Represent individual potential future price paths based on GBM. A wider spread indicates higher volatility.
        Expected Value (EV) Line (Goldenrod):
            Shows the mean projected price at each future bar, providing a central trend.
        Confidence Bands (Green & Red):
            Indicate the statistical range (95% confidence) within which the price is expected to remain.
        EV of EV Line (Dotted Line - Goldenrod):
            Reflects the running average of EV values, offering a smoothed perspective of expected price trends over the projection period.
        Current Price (White):
            Serves as a benchmark for assessing how actual prices compare to projected paths.
Practical Applications
    Risk Management:
        Confidence Bands: Help in identifying potential support and resistance levels based on statistical confidence intervals.
        EV Path: Assists in setting realistic target prices and stop-loss levels aligned with projected expectations.
    Trend Analysis:
        EV of EV Line: Offers a smoothed trendline, aiding in identifying overarching market directions amidst price volatility. Indicative of the population mean/overall trend of the data since your anchor point.
    Scenario Planning:
        Simulation Lines: Enable traders to visualize multiple potential outcomes, fostering better decision-making under uncertainty.
    Performance Evaluation:
        Comparing Actual vs. Projected Prices: Assess how actual price movements align with projected scenarios, refining trading strategies over time.
Mathematical and Statistical Insights
    Simulation Integrity:
        Independence: Each simulation path is generated independently, ensuring unbiased and diverse projections.
        Randomness: Utilizes a Gaussian random number generator to introduce variability in diffusion terms, mimicking real market randomness.
    Statistical Reliability:
        Central Limit Theorem (CLT): By simulating a sufficient number of paths (e.g., 30), the sample mean (EV) converges to the population mean, ensuring reliable EV and confidence band calculations.
        Variance Calculation: Accurate computation of variance from simulation data ensures precise confidence intervals.
    Dynamic Projections:
        Running Average (EV of EV): Provides a cumulative perspective, allowing traders to observe how the average expectation evolves as the projection progresses.
Customization and Enhancements
    Adjustable Parameters:
        Tailor the projection length and simulation count to match your trading style and analysis depth.
    Visual Customization:
        Modify line colors, styles, and transparency to enhance clarity and fit chart aesthetics.
    Extended Statistical Metrics:
        Future iterations can incorporate additional metrics like median projections, skewness, or alternative confidence intervals.
    Dynamic Recalculation:
        Implement logic to automatically update projections as new data becomes available, ensuring real-time relevance.
Performance Considerations
    Object Count Management:
        High simulation counts and extended projection periods can lead to a significant number of graphical objects, potentially slowing down chart performance.
        Solution: Utilize display toggles effectively and optimize projection parameters to balance detail with performance.
    Computational Efficiency:
        The script employs efficient array handling and conditional plotting to minimize unnecessary computations and object creation.
Conclusion
The Anchored GBM Projections + EV & Confidence Bands indicator is a robust tool for traders seeking to forecast potential future price movements using statistical models. By integrating Geometric Brownian Motion simulations with expected value calculations and confidence intervals, it offers a comprehensive view of possible market scenarios. The addition of the "EV of EV" line further enhances analytical depth by providing a running average of expected values, aiding in trend identification and strategic decision-making.
Hope it helps!
Dix$on's Weighted Volume FlowDixson's Weighted Volume Flow
Dixson's Weighted Volume Flow is a technical indicator designed to analyze and visualize the distribution of buy and sell volume within a given timeframe. It dynamically calculates the proportional allocation of volume based on price action within each bar, providing insights into market sentiment and activity. This indicator displays horizontal volume bars in a separate pane and annotates them with precise volume values.
How It Works
1. Volume Allocation:
   - The indicator calculates buy and sell volume using the following formulas:
     - Buy Volume = (Close - Low) / (High - Low) Total Volume
     - Sell Volume = (High - Close) / (High - Low)  Total Volume
   - These formulas allocate volume proportionally based on the bar's price range, attributing more volume to buying or selling depending on the relationship between the close, high, and low prices.
2. Dynamic Scaling:
   - The buy and sell volumes are scaled relative to their combined total for the period.
   - The resulting values determine the length of the horizontal bars, providing a comparative view of buy and sell activity.
3. Bar Visualization:
   - Buy Volume Bars: Displayed as green horizontal bars.
   - Sell Volume Bars: Displayed as red horizontal bars.
   - The lengths of the bars represent the dominance of buy or sell volume, scaled dynamically within the pane.
4. Labels:
   - Each bar is annotated with a label showing its calculated buy or sell volume value.
5. Timeframe Adjustment:
   - The indicator uses the request.security() function to fetch data from the selected timeframe, allowing users to customize their analysis for intraday, daily, or longer-term trends.
6. Customization Options:
   - Enable or disable the indicator using a toggle.
   - Adjust colors for the buy/sell bars and text labels to suit your chart theme.
How to Use It
1. Enable the Indicator:
   - Activate the indicator using the "Enable/Disable" toggle in the settings.
2. Select a Timeframe:
   - Choose the timeframe for analysis (e.g., 1-minute, 1-hour, daily). The indicator fetches volume data specific to the selected timeframe.
3. Interpret the Visualization:
   - Compare Bar Lengths:
     - Longer buy volume bars (green) indicate stronger buying activity.
     - Longer sell volume bars (red) suggest dominant selling pressure.
   - Labels:
     - Use the labels to view the exact buy and sell volume values for precise analysis.
4. Combine with Other Tools:
   - Use the indicator alongside price action analysis, support/resistance levels, or trend indicators to confirm market sentiment and detect potential reversals.
5. Monitor Imbalances:
   - Significant disparities between buy and sell volume can signal shifts in market sentiment, such as the end of a trend or the start of a breakout.
Practical Applications
- Trend Confirmation:
  - Align the dominance of buy or sell volume with price trends to confirm market direction.
  
- Reversal Signals:
  - Watch for volume imbalances or a sudden shift in the dominance of buy or sell volume to identify potential reversals.
- High-Activity Zones:
  - Identify areas with increased volume to anticipate significant price movements or key support/resistance interactions.
Dixson's Weighted Volume Flow provides a clear and systematic way to analyze market activity by visualizing the dynamics of buy and sell volume. It is particularly useful for traders looking to enhance their understanding of volume-based sentiment and its impact on price movements.
Wick/Tail Candle MeasurementsThis indicator runs on trading view. It was programmed with pine script v5. 
Once the indicator is running you can scroll your chart to any year or date on the chart, then for the input select the date your interested in knowing the length of the tails and wicks from a bar and their lengths are measured in points. 
To move the measurement, you can select the vertical bar built into the indicator AFTER clicking the green label and moving it around using the vertical bar *only*. You must click the vertical bar in the middle of the label to move the indicator calculation to another bar. You can also just select the date using the input as mentioned. This indicator calculates just one bar at a time.
measurements are from bar OPEN to bar HIGH for measured WICKS regardless of the bar being long or short and from bar OPEN to bar LOW for measured TAILS also regardless of the bar being long or short.
This indicator calculates tails and wicks including the bar body in the calculations. Basically showing you how much the market moved in a certain direction for the entire duration of that Doji candle. 
Its designed to measure completed bars on the daily futures charts. (Dow Jones, ES&P500, Nasdaq, Russell 2000, etc)  Although it may work well on other markets. The indicator could easily be tweaked in order to work well with other markets. It is not designed for forex markets currently.
Bull Bear Power With EMA FilterDescription of Indicator:
This Pine Script indicator colors price bars based on the open price in relation to custom moving averages (EMA/SMA), Bull/Bear Power (BBPower), and an optional VWAP filter. The bar colors help identify bullish and bearish conditions with added visual cues for price positioning relative to VWAP.
Key Features:
Customizable Moving Averages (EMA/SMA):
The user can select between EMA or SMA for both short-term and long-term moving averages.
Default moving averages are set to 5 (short-term) and 9 (long-term) but can be adjusted by the user.
Bullish Condition (Blue or Purple Bars):
A bar is colored blue if the following conditions are met:
The open price is above both the short-term and long-term moving averages.
The short-term moving average (MA 1) is above the long-term moving average (MA 2).
BBPower (open price minus the 13-period EMA) is positive, indicating bullish strength.
If the VWAP filter is enabled and the price opens below VWAP, the bullish bars will turn purple.
Bearish Condition (Yellow or Orange Bars):
A bar is colored yellow if the following conditions are met:
The open price is below both the short-term and long-term moving averages.
The short-term moving average (MA 1) is below the long-term moving average (MA 2).
BBPower is negative or zero, indicating bearish market conditions.
If the VWAP filter is enabled and the price opens above VWAP, the bearish bars will turn orange.
VWAP Filter (Optional):
An optional filter allows the user to add VWAP (Volume-Weighted Average Price) to the bar coloring logic.
When the VWAP filter is enabled, it provides additional information about price positioning relative to VWAP, turning bullish bars purple and bearish bars orange depending on whether the price opens above or below VWAP.
Usage:
Bullish Trend: Look for blue or purple bars to identify potential bullish momentum.
Bearish Trend: Look for yellow or orange bars to spot bearish conditions in the market.
The indicator allows users to customize the length and type of moving averages (EMA or SMA), as well as decide whether to apply the VWAP filter.
This indicator provides traders with clear visual signals to quickly assess the strength of bullish or bearish conditions based on the price's position relative to custom moving averages, BBPower, and VWAP, helping with trend identification and potential trade setups.
Trend and RSI Bias FusionTrend and RSI Bias Fusion Indicator 
 This is my first ever indicator. I created this indicator for myself. I was inspired by the indicators created by Bjorgum, Duyck and QuantTherapy and decided to create multiple indicators that either work well combined with their indicators or something new that applies some of their indicator concepts. I decided to share this because I believe in learning and earing together as a community. I will later share the rest of the indicators I have created. This is my first time ever sharing any indicator so if you guys have any questions or suggestions write them.  
 Overview 
The "Trend and RSI Bias Fusion" indicator is a versatile tool designed to help traders identify key market trends, potential reversals, momentum shifts, and RSI-based pullbacks. This indicator fuses trend analysis and RSI bias into a single, comprehensive visual, making it easier to make informed trading decisions across various timeframes and market conditions.
 Features 
 Dual Timeframe Analysis:  Combines trend analysis on a higher timeframe (e.g., Daily) with RSI analysis on a lower timeframe (e.g., 4-Hour), providing a more granular view of market conditions. You can, however, choose any timeframe you want for instance 12hr with trend and 2hr RSI analysis.
 Trend and Momentum Visualization:  The indicator uses Exponential Moving Averages (EMAs) to determine trend direction and colors the chart background to reflect bullish or bearish trends, along with momentum strength.
 RSI Bias Detection:  Automatically identifies overbought and oversold conditions using the RSI, providing a clear indication of potential market reversals or continuations.
Color-Coded Bars: Optionally color codes bars based on either trend direction or RSI bias, giving you a quick visual cue of the market's state.
 Reversal Markers:  Displays trend reversal markers on the chart when the short-term EMA crosses over or under the long-term EMA.
 Calculation Details 
 Exponential Moving Averages (EMAs):  The indicator calculates short-term and long-term EMAs using the closing prices.
The crossover between these EMAs is used to determine the trend direction:
Short-Term EMA: Typically a 14-period EMA.
Long-Term EMA: Typically a 50-period EMA.
 Momentum:  Calculated using the RSI and then centered around zero by subtracting 50. This allows the indicator to distinguish between positive and negative momentum.
 RSI Bias:  The RSI is calculated on a lower timeframe to detect overbought (above 60) and oversold (below 40) conditions, which are used to determine the bias:
RSI Above 60: Indicates potential overbought conditions (bearish bias).
RSI Below 40: Indicates potential oversold conditions (bullish bias).
 How to Use the Indicator 
 Select Your Timeframes:  Choose your preferred trend timeframe (e.g., Daily) and RSI timeframe (e.g., 4-2 Hour) in the indicator settings. These should match your trading strategy and the asset class you're analyzing.
 Interpret Trend and Momentum 
 Background Color:  The background color reflects the current trend direction:
 Green/Lime:  Uptrend, with lime indicating positive momentum.
 Red/Maroon:  Downtrend, with maroon indicating positive momentum within a downtrend.
 Momentum Histogram:  The histogram plot shows momentum, color-coded by the trend. A histogram above zero with green/lime indicates bullish momentum, while below zero with red/maroon indicates bearish momentum.
  
Image above: Both RSI and Trend are set to daily, uses RSI bar color
 Read RSI Bias: 
The RSI bias line helps identify the current market state relative to overbought or oversold levels. The RSI value is plotted on the chart, with lines at 60 and 40 to mark these levels.
When the RSI crosses above 60, it suggests a bearish bias; crossing below 40 suggests a bullish bias.
 Use Reversal Markers:  The indicator places small circles on the chart at points where the short-term EMA crosses the long-term EMA, signaling potential trend reversals.
Bar Color Customization:
You can choose to color the bars based on either the trend or the RSI bias in the indicator settings. In the Images below I have changed the colors to fit my personal style , Blue for uptrend and Pink for downtrend:
 Trend-Based:  Bars will reflect the trend direction (green for uptrend or in this case blue, red for downtrend or in this case pink).
 RSI-Based:  Bars will reflect RSI conditions (yellow for overbought, maroon for oversold).
  
Image above: RSI is set to 4hr and Trend is set to daily, uses RSI bar color
  
Image above: RSI is set to 4hr and Trend is set to daily, uses Trend bar color
  
Image above: Both RSI and Trend are set to daily, uses RSI bar color
  
Image above: Both RSI and Trend are set to daily, uses Trend bar color
  
Image above: Both RSI and Trend are set to daily, without bar color
   
Image above: Both RSI and Trend are set to daily, how it looks on a clean chart
 Example Use Case Swing Traders: 
For instance, if you're trading a 4-hour chart of USDCHF:
Set the trend timeframe to Daily and the RSI timeframe to 4-Hour.
Watch for background color shifts and reversal markers to determine trend direction.
Use RSI bias to time your entries and exits, especially around overbought/oversold levels.
Enable bar coloring to quickly see when conditions favor either trend continuation or reversal.
This indicator is particularly effective for swing traders and those who want to align their trades with higher timeframe trends while using momentum and RSI for entry and exit signals.
 For Day Traders 
 Timeframe Selection: 
Trend Timeframe: Set to a higher intraday timeframe such as the 1 or 2 Hour chart.
RSI Timeframe: Set to a shorter timeframe like 15-10 Minutes or 5-Minutes to capture finer details of intraday momentum shifts.
 Using the Indicator: 
Trend Identification: Day traders can use the background color to quickly identify whether the market is in a bullish or bearish trend on the 1-Hour chart. A green background suggests looking for long opportunities, while a red background suggests short opportunities.
Momentum Analysis: The histogram can help day traders gauge the strength of the current trend. For example, if the histogram is green and above zero, the trader may consider buying pullbacks within the trend.
 RSI Bias:  Monitor RSI levels on the lower timeframe (e.g., 15-Minutes). If the RSI crosses below 40, it indicates an oversold condition, potentially signaling a buying opportunity, especially if it aligns with a bullish trend on the higher timeframe.
 Trade Execution: 
Look for entries when the RSI shows a reversal or pullback in the direction of the higher timeframe trend.
Use the trend reversal markers to confirm potential intraday reversals, adding extra confidence to trade setups.
 For Scalpers 
 Timeframe Selection: 
 Trend Timeframe:   Set to a short intraday timeframe like 15-Minutes or 5-Minutes.
RSI Timeframe: Use an even shorter timeframe, such as 1-Minute, to capture rapid price movements.
 Final Notes: 
The "Trend and RSI Bias Fusion" indicator is a powerful tool that combines trend analysis, momentum assessment, and RSI insights into one cohesive package. By integrating these different aspects, the indicator helps traders navigate complex market environments with greater clarity and confidence. Customize the settings to fit your specific trading style and market and use it to stay ahead of market trends and potential reversals.
My Scripts/Indicators/Ideas /Systems that I share are only for educational purposes!
Brooks Always In [KintsugiTrading]Brooks Always In 
 Overview: 
The "Brooks Always In Indicator" by KintsugiTrading is a tool designed for traders who follow price action methodologies inspired by Al Brooks. This indicator identifies key bar patterns and breakouts, plots an Exponential Moving Average (EMA), and highlights consecutive bullish and bearish bars. It is intended to assist traders in making informed decisions based on price action dynamics.
 Features: 
 Consecutive Bar Patterns: 
Identifies and highlights consecutive bullish and bearish bars.
Differentiates between bars that are above/below the EMA and those that are not.
 Customizable EMA: 
Option to display an Exponential Moving Average (EMA) with user-defined length and offset.
The EMA can be smoothed using various methods such as SMA, EMA, SMMA (RMA), WMA, and VWMA.
 Breakout Patterns: 
Recognizes bullish and bearish breakout bars and outside bars.
Tracks inside bars and prior bar conditions to better understand the market context.
 Customizable Display: 
Users can display or hide the EMA, consecutive bar patterns, and consecutive bars relative to the moving average.
 How to Use: 
 Customize Settings: 
First, I like to navigate to the top right corner of the chart (bolt icon), and change both the bull and bear body color to match the background (white/black) - this helps the user visualize the indicator far better.
Next, Toggle to display EMA, consecutive bar patterns, and consecutive bars relative to the moving average using the provided input options.
Adjust the EMA length, source, and offset as per your trading strategy.
Select the smoothing method and length for the EMA if desired.
 Analyze Key Patterns: 
Observe the highlighted bars on the chart to identify consecutive bullish and bearish patterns.
Use the plotted EMA to gauge the general trend and analyze the relationship between price bars and the moving average.
 Informed Decision Making: 
Utilize the identified bar patterns and breakouts to make informed trading decisions, such as identifying potential entry and exit points based on price action dynamics.
Good luck with your trading!
HTF Descending TriangleHTF Descending Triangle  aims at detecting descending triangles using higher time frame data, without repainting nor misalignment issues.
Descending triangles are defined by a falling upper trend line and an horizontal lower trend line. It is a chart pattern used in technical analysis to predict the continuation of a downtrend.
This indicator can be useful if you, like me, believe that higher time frames can offer a broader perspective and provide clearer signals, smoothing out market noise and showing longer-term trends.
You can change the indicator settings as you see fit to tighten or loosen the detection, and achieve the best results for your use case.
 Features 
 
 It draws the detected descending triangle on the chart.
 It supports alerting when a detection occurs.
 It allows for setting the higher time frame to run the detection on.
 It allows for setting the minimum number of consecutive valid higher time frame bars to fit the pattern criteria.  
 It allows for setting a low factor detection criteria to apply on higher time frame bars low as a proportion of the distance between the reference bar low and open/close.
 It allows for turning on an adjustment of the triangle using highest/lowest values within valid higher time frame bars.
 
 Settings 
 
 Higher Time Frame  dropdown: Selects higher time frame to run the detection on. It must be higher than, and a multiple of, the chart's timeframe.
 Valid Bars Minimum  field: Sets minimum number of consecutive valid higher time frame bars to fit the pattern criteria.
 Low Factor  checkbox: Turns on/off low factor detection criteria.
 Low Factor  field: Sets low factor to apply on higher time frame bars low as a proportion of the distance between the reference bar low and open/close.
 Adjust Triangle  checkbox: Turns on/off triangle adjustment using highest/lowest values within valid higher time frame bars.
 
 Detection Algorithm Notes 
The detection algorithm recursively selects a higher time frame bar as reference. Then it looks at the consecutive higher time frame bars (as per the requested number of minimum valid bars) as follows:
 
 High must be lower than previous bar.
 Open/close min value must be higher than reference bar low.
 When low factor criteria is turned on, low must be lower than reference bar open/close min value minus low factor proportion of the distance between reference bar low and open/close min value.
HTF Ascending TriangleHTF Ascending Triangle  aims at detecting ascending triangles using higher time frame data, without repainting nor misalignment issues.
Ascending triangles are defined by an horizontal upper trend line and a rising lower trend line. It is a chart pattern used in technical analysis to predict the continuation of an uptrend.
This indicator can be useful if you, like me, believe that higher time frames can offer a broader perspective and provide clearer signals, smoothing out market noise and showing longer-term trends.
You can change the indicator settings as you see fit to tighten or loosen the detection, and achieve the best results for your use case.
 Features 
 
 It draws the detected ascending triangle on the chart.
 It supports alerting when a detection occurs.
 It allows for setting the higher time frame to run the detection on.
 It allows for setting the minimum number of consecutive valid higher time frame bars to fit the pattern criteria.  
 It allows for setting a high factor detection criteria to apply on higher time frame bars high as a proportion of the distance between the reference bar high and open/close.
 It allows for turning on an adjustment of the triangle using highest/lowest values within valid higher time frame bars.
 
 Settings 
 
 Higher Time Frame  dropdown: Selects higher time frame to run the detection on. It must be higher than, and a multiple of, the chart's timeframe.
 Valid Bars Minimum  field: Sets minimum number of consecutive valid higher time frame bars to fit the pattern criteria.
 High Factor  checkbox: Turns on/off high factor detection criteria.
 High Factor  field: Sets high factor to apply on higher time frame bars high as a proportion of the distance between the reference bar high and close/open.
 Adjust Triangle  checkbox: Turns on/off triangle adjustment using highest/lowest values within valid higher time frame bars.
 
 Detection Algorithm Notes 
The detection algorithm recursively selects a higher time frame bar as reference. Then it looks at the consecutive higher time frame bars (as per the requested number of minimum valid bars) as follows:
 
 Low must be higher than previous bar.
 Open/close max value must be lower than reference bar high.
 When high factor criteria is turned on, high must be higher than reference bar open/close max value plus high factor proportion of the distance between reference bar high and open/close max value.
regressionsLibrary   "regressions" 
This library computes least square regression models for polynomials of any form for a given data set of x and y values.
 fit(X, y, reg_type, degrees) 
  Takes a list of X and y values and the degrees of the polynomial and returns a least square regression for the given polynomial on the dataset.
  Parameters:
     X (array) : (float )    X inputs for regression fit.
     y (array) : (float ) 	 y outputs for regression fit.
     reg_type (string) : (string)	 The type of regression. If passing value for degrees use reg.type_custom
     degrees (array) : (int )      The degrees of the polynomial which will be fit to the data. ex: passing array.from(0, 3) would be a polynomial of form c1x^0 + c2x^3 where c2 and c1 will be coefficients of the best fitting polynomial.
  Returns: (regression) returns a regression with the best fitting coefficients for the selecected polynomial
 regress(reg, x) 
  Regress one x input.
  Parameters:
     reg (regression) : (regression) The fitted regression which the y_pred will be calulated with.
     x (float) : (float)      The input value cooresponding to the y_pred.
  Returns: (float)		 The best fit y value for the given x input and regression.
 predict(reg, X) 
  Predict a new set of X values with a fitted regression. -1 is one bar ahead of the realtime
  Parameters:
     reg (regression) : (regression) 		The fitted regression which the y_pred will be calulated with.
     X (array) 
  Returns: (float )		 	The best fit y values for the given x input and regression.
 generate_points(reg, x, y, left_index, right_index) 
  Takes a regression object and creates chart points which can be used for plotting visuals like lines and labels.
  Parameters:
     reg (regression) : (regression)    Regression which has been fitted to a data set.
     x (array) : (float )		x values which coorispond to passed y values
     y (array) : (float )		y values which coorispond to passed x values
     left_index (int) : (int)      		The offset of the bar farthest to the realtime bar should be larger than left_index value.
     right_index (int) : (int)      		The offset of the bar closest to the realtime bar should be less than right_index value.
  Returns: (chart.point )	 Returns an array of chart points
 plot_reg(reg, x, y, left_index, right_index, curved, close, line_color, line_width) 
  Simple plotting function for regression	for more custom plotting use generate_points() to create points then create your own plotting function.
  Parameters:
     reg (regression) : (regression) 	Regression which has been fitted to a data set.
     x (array) 
     y (array) 
     left_index (int) : (int)      		The offset of the bar farthest to the realtime bar should be larger than left_index value.
     right_index (int) : (int)      		The offset of the bar closest to the realtime bar should be less than right_index value.
     curved (bool) : (bool)  		If the polyline is curved or not.
     close (bool) : (bool)  		If true the polyline will be closed.
     line_color (color) : (color) 		The color of the line.
     line_width (int) : (int) 			The width of the line.
  Returns: (polyline)      The polyline for the regression.
 series_to_list(src, left_index, right_index) 
  Convert a series to a list. Creates a list of all the cooresponding source values
from left_index to right_index. This should be called at the highest scope for consistency.
  Parameters:
     src (float) : (float ) 	The source the list will be comprised of.
     left_index (int) : (float )   The left most bar (farthest back historical bar) which the cooresponding source value will be taken for.
     right_index (int) : (float )   The right most bar closest to the realtime bar which the cooresponding source value will be taken for.
  Returns: (float )  	An array of size left_index-right_index
 range_list(start, stop, step) 
  Creates an from the start value to the stop value.
  Parameters:
     start (int) : (float ) 	The true y values.
     stop (int) : (float )   The predicted y values.
     step (int) : (int)   	Positive integer. The spacing between the values. ex: start=1, stop=6, step=2:  
  Returns: (float )  	An array of size stop-start
 regression 
  Fields:
     coeffs (array__float) 
     degrees (array__float) 
     type_linear (series__string) 
     type_quadratic (series__string) 
     type_cubic (series__string) 
     type_custom (series__string) 
     _squared_error (series__float) 
     X (array__float)






















