TargetExcursionQueueLibLibrary "TargetExcursionQueueLib"
helper lib for targetExcursionLib
f_queue_new(horizon)
Construct a fixed ring. Horizon is clamped to the supported 1..198 range.
Parameters:
horizon (int)
method advance(queue, pathHigh, pathLow, pathClose, pathValid, currentBar)
Update every unresolved path with this confirmed chart bar and
resolve the oldest origin exactly H chart bars after it was accepted.
Invalid path bars invalidate the affected target instead of hiding a gap.
Namespace types: PendingQueue
Parameters:
queue (PendingQueue)
pathHigh (float)
pathLow (float)
pathClose (float)
pathValid (bool)
currentBar (int)
method enqueue(queue, direction, origin, scale, currentBar)
Freeze one valid, non-neutral origin after older origins have advanced.
Namespace types: PendingQueue
Parameters:
queue (PendingQueue)
direction (int)
origin (float)
scale (float)
currentBar (int)
PendingOrigin
Fields:
originBar (series int)
resolutionBar (series int)
direction (series int)
origin (series float)
scale (series float)
maxHigh (series float)
minLow (series float)
pathComplete (series bool)
ResolvedExcursion
Fields:
resolved (series bool)
valid (series bool)
timingExact (series bool)
originBar (series int)
resolutionBar (series int)
direction (series int)
origin (series float)
scale (series float)
mae (series float)
mfe (series float)
closeReturn (series float)
directionalCloseReturn (series float)
PendingQueue
Fields:
slots (array)
capacity (series int)
horizon (series int)
readHead (series int)
writeHead (series int)
count (series int)
acceptedCount (series int)
resolvedCount (series int)
invalidResolvedCount (series int)
lastResolvedBar (series int) Perpustakaan

TargetExcursionStatsLibLibrary "TargetExcursionStatsLib"
helper for targetExcursionLib
f_density_new(gridSize, outcomeCap, smoothing, halfLife, familyCode, shrinkageAlpha)
Construct one independent density state.
Parameters:
gridSize (int)
outcomeCap (float)
smoothing (float)
halfLife (float)
familyCode (int)
shrinkageAlpha (float)
method advance(state, currentBar)
Advance all six streams causally to currentBar.
Namespace types: DensityState
Parameters:
state (DensityState)
currentBar (int)
method observe(state, direction, mae, mfe, resolutionBar)
Add one resolved, direction-conditioned excursion observation.
MAE and MFE are normalized, nonnegative values frozen by the queue.
Namespace types: DensityState
Parameters:
state (DensityState)
direction (int)
mae (float)
mfe (float)
resolutionBar (int)
method support(state, direction, isMae)
Effective sample support for a direction and outcome stream.
Namespace types: DensityState
Parameters:
state (DensityState)
direction (int)
isMae (bool)
method directionSupport(state, direction)
Minimum of current direction's MAE/MFE effective supports.
Namespace types: DensityState
Parameters:
state (DensityState)
direction (int)
method estimate(state, direction, isMae)
Quantiles, mode, modal probability and support for one stream.
Namespace types: DensityState
Parameters:
state (DensityState)
direction (int)
isMae (bool)
method probabilityAt(state, direction, isMae, value)
Smoothed probability mass at the bin containing value.
Namespace types: DensityState
Parameters:
state (DensityState)
direction (int)
isMae (bool)
value (float)
Histogram
Fields:
bins (array)
weight (series float)
weightSq (series float)
DensityState
Fields:
pooledMae (Histogram)
pooledMfe (Histogram)
longMae (Histogram)
longMfe (Histogram)
shortMae (Histogram)
shortMfe (Histogram)
gridSize (series int)
outcomeCap (series float)
smoothing (series float)
halfLife (series float)
familyCode (series int)
shrinkageAlpha (series float)
lastDecayBar (series int)
lastResolvedBar (series int)
resolvedCount (series int)
longResolvedCount (series int)
shortResolvedCount (series int)
DensityEstimate
Fields:
q10 (series float)
q50 (series float)
q80 (series float)
q90 (series float)
mode (series float)
modeProbability (series float)
effectiveSupport (series float) Perpustakaan

Indikator

Compact Trending Scanner Tiene configurados:
SPY, AMD, AAPL, NVDA, TSLA, GOOGL, META, AMZN, TSM, PLTR, MRVL, SNDK, MU, INTC, HOOD, ARM, DELL y SPCX
Los ordena automáticamente según una combinación de movimiento porcentual, ADX y alineación. Muestra:
Precio.
Movimiento porcentual contra el cierre anterior.
ADX.
Above, Below, Inside o Cross respecto al día anterior.
Posición respecto al premarket.
Posición respecto al rango de 5 minutos.
RVOL de la vela contra las últimas 20 velas.
Tendencia Bull, Bear o Wait. Indikator

Indikator

Indikator

MTF Bull/Bear TableMTF Bull/Bear Table — Multi-Timeframe Confluence Scanner
OVERVIEW
This tool scans a custom watchlist of symbols across five timeframes at once
(5m, 15m, 1h, 4h, 1D) and displays the result as a single table, so you can
read directional confluence across your whole list at a glance instead of
flipping through charts one by one.
For each symbol/timeframe pair, the script classifies trend state as:
BULL — price is above both the fast MA and the slow MA
BEAR — price is below both the fast MA and the slow MA
NEUTRAL — price is on opposite sides of the two MAs (mixed signal)
By default the fast MA is a 20-period SMA and the slow MA is a 200-period
SMA, the classic short-term/long-term trend pair — price above both means
both timeframes agree the trend is up, price below both means they agree
it's down, and a mixed reading flags a timeframe that's transitioning or
consolidating. Both MA lengths are adjustable in the settings.
HOW TO READ THE TABLE
Each row is one symbol. Reading left to right:
TICKER the instrument
PRICE current live price (read from the daily context; it
updates in real time and is not a fixed daily close)
24H% / 1H% / 4H% percentage change since the last completed candle close
on that timeframe (daily / 1h / 4h respectively), colored
by sign. This is not a fixed rolling window — the actual
elapsed time varies depending on where price currently
sits within the still-forming candle (e.g. "24H%" can
reflect anywhere from a few minutes to nearly 24 hours
of movement, depending on the time of day).
5M / 15M / 1H / 4H / D trend state for each timeframe, color-coded:
green = BULL, red = BEAR, gray = NEUTRAL
Reading a row across the five timeframe columns shows you confluence at a
glance: five green cells is trend alignment from intraday noise all the way
up to the daily chart — a high-conviction directional read. A mix of colors
means timeframes disagree, which typically means either a transition in
progress or a level currently being tested.
This is a screening and context tool, not a standalone entry signal — it
tells you which timeframes agree and which don't, not where to place a
trade. Combine it with your own setup criteria (structure, volume, price
action) for actual entries.
SETTINGS
Symbols comma-separated list with full exchange prefix
(e.g. HYPERLIQUID:BTCUSDC.P). TradingView cannot read your
saved watchlist programmatically, so the list is entered
directly in the script settings.
Fast / Slow MA length default 20 / 200, adjustable
Table position corner of the chart the table is drawn in
Show price columns toggle price/change columns on or off
LIMITATIONS
TradingView caps every script at a fixed number of unique request.security()
calls — 40 on non-Pro plans, 64 on Pro/Expert/Ultimate. This script uses one
call per symbol per timeframe (5 timeframes), so the practical ceiling is
roughly 8 symbols on a non-Pro plan and ~12 on Pro. Trim the symbol list to
fit your plan; the script will show "N/A" for any symbol it fails to resolve
rather than breaking the whole table.
Percentage-change values for 24H/1H/4H are pulled from the same requests
already used for the trend classification, so they add no extra request
cost beyond the base 5-per-symbol. Indikator

TargetExcursionLibLibrary "TargetExcursionLib"
Parent supplies origin price/scale, direction, and path high/low/close series.
Library derives no hidden source data.
Returns bands.ready, bands.status, bands.effectiveSupport, and bands.resolvedCount.
Before minimum support: status is exactly "band stats not ready yet" and all band levels are na.
f_input(direction, originPrice, originScale, predictionValid, directionProbability, externalReliability)
Construct a generic target input from series values.
Parameters:
direction (int)
originPrice (float)
originScale (float)
predictionValid (bool)
directionProbability (float)
externalReliability (float)
f_model_new(gridSize, outcomeCap, smoothing, halfLife, family, shrinkageAlpha, minSupport, supportScale, minTransparency, maxTransparency, transparencyGamma)
Construct an independent stateful model instance.
Parameters:
gridSize (int)
outcomeCap (float)
smoothing (float)
halfLife (float)
family (series DensityFamily)
shrinkageAlpha (float)
minSupport (float)
supportScale (float)
minTransparency (int)
maxTransparency (int)
transparencyGamma (float)
f_update(model, signal, pathHigh, pathLow, pathClose, horizon, currentBar, confirmed)
Parameters:
model (TargetModel)
signal (TargetInput)
pathHigh (float)
pathLow (float)
pathClose (float)
horizon (int)
currentBar (int)
confirmed (bool)
TargetInput
Fields:
direction (series int)
originPrice (series float)
originScale (series float)
predictionValid (series bool)
directionProbability (series float)
externalReliability (series float)
TargetBands
Fields:
ready (series bool)
status (series string)
direction (series int)
originPrice (series float)
originScale (series float)
mfeQ10 (series float)
mfeQ50 (series float)
mfeQ80 (series float)
mfeQ90 (series float)
mfeMode (series float)
maeQ10 (series float)
maeQ50 (series float)
maeQ80 (series float)
maeQ90 (series float)
maeMode (series float)
mfePriceQ10 (series float)
mfePriceQ50 (series float)
mfePriceQ80 (series float)
mfePriceQ90 (series float)
mfePriceMode (series float)
maePriceQ10 (series float)
maePriceQ50 (series float)
maePriceQ80 (series float)
maePriceQ90 (series float)
maePriceMode (series float)
effectiveSupport (series float)
intervalCoverageEstimate (series float)
reliability (series float)
transparency (series int)
pendingCount (series int)
resolvedCount (series int)
lastResolvedBar (series int)
PendingTarget
Fields:
originBar (series int)
resolutionBar (series int)
direction (series int)
originPrice (series float)
originScale (series float)
maxHigh (series float)
minLow (series float)
TargetModel
Fields:
pending (array)
pooledMae (array)
pooledMfe (array)
longMae (array)
longMfe (array)
shortMae (array)
shortMfe (array)
pooledMaeWeight (series float)
pooledMaeWeightSq (series float)
pooledMfeWeight (series float)
pooledMfeWeightSq (series float)
longMaeWeight (series float)
longMaeWeightSq (series float)
longMfeWeight (series float)
longMfeWeightSq (series float)
shortMaeWeight (series float)
shortMaeWeightSq (series float)
shortMfeWeight (series float)
shortMfeWeightSq (series float)
gridSize (series int)
outcomeCap (series float)
smoothing (series float)
halfLife (series float)
family (series DensityFamily)
shrinkageAlpha (series float)
minSupport (series float)
supportScale (series float)
minTransparency (series int)
maxTransparency (series int)
transparencyGamma (series float)
lastDecayBar (series int)
lastResolvedBar (series int)
resolvedCount (series int) Perpustakaan

Clean EMA Pullback Indicator v6The Clean EMA Pullback Indicator v6 is a trend-following and pullback confirmation indicator designed for traders who want a simple, objective way to identify high-probability continuation trades. It combines moving average trend analysis, market structure, multi-timeframe confirmation, and price action into a single, easy-to-read indicator.
Unlike indicators that generate frequent signals, this script is designed to filter out lower-quality setups and only alert when multiple conditions align.
Features
📈 Trend Identification
Dynamic 200 EMA that changes color:
🟢 Green = Bullish trend
🔴 Red = Bearish trend
20 EMA Pullback Channel to identify retracement zones.
50 EMA for additional trend alignment and confirmation.
📊 Market Structure
Automatically identifies key swing structure:
Higher High (HH)
Higher Low (HL)
Lower High (LH)
Lower Low (LL)
This helps traders visually confirm whether the market is making bullish or bearish price structures.
🎯 Entry Signals
The indicator generates:
BUY signals after a confirmed bullish pullback and breakout.
SELL signals after a confirmed bearish pullback and breakdown.
Signals are based on trend direction, EMA alignment, pullback confirmation, and market structure—not simply moving average crossovers.
🔄 Optional Re-Entry Signals
Optional re-entry triangles identify opportunities to rejoin an existing trend after a healthy pullback, allowing traders to participate in continuation moves without chasing price.
🕯 Trend Candle Coloring
Candles are color-coded to quickly show whether momentum favors buyers or sellers, making trend recognition easier at a glance.
📋 Multi-Timeframe Dashboard
Displays trend direction for:
15 Minute
30 Minute
4 Hour
The dashboard also provides an overall alignment status:
✅ Strong Buy
✅ Strong Sell
⚠ Mixed
This helps traders avoid trading against higher-timeframe momentum.
📅 Previous Day Range
Plots:
Previous Day High
Previous Day Low
These levels often act as key support, resistance, breakout, or reversal areas.
📦 Trend-Filtered Fair Value Gaps (FVG)
Automatically highlights Fair Value Gaps that align with the current 200 EMA trend, helping traders focus on higher-probability imbalance zones while filtering out counter-trend gaps.
📏 ATR Trade Management
Built-in ATR-based trade management automatically plots:
Entry level
Stop Loss
Take Profit 1
Take Profit 2
This provides a consistent, rules-based framework for managing risk and reward.
Best Used For
Futures (MNQ, NQ, RTY, M2K, ES, MES, GC, MGC)
Forex
Stocks
ETFs
Cryptocurrency
Recommended for intraday trading on 1-minute, 3-minute, 5-minute, and 15-minute charts while using higher timeframes for trend confirmation.
Trading Philosophy
This indicator is built around a simple principle:
Trade with the trend, wait for the pullback, and enter only after the market confirms continuation.
Rather than predicting market direction, the script is designed to help traders remain patient, reduce emotional decision-making, and focus on disciplined, high-quality setups.
Disclaimer: This indicator is intended as a decision-support tool and should not be considered financial advice. Always practice sound risk management and test any strategy thoroughly before using it in a live trading environment. Indikator

SVKO CFD Symbol MapperSVKO CFD Symbol Mapper resolves broker CFD tickers to their native TradingView symbols and performs reverse lookups for compatible indicators. It provides one shared mapping source instead of duplicating mappings across companion scripts.
█ OVERVIEW
This is a visually silent helper indicator. It does not draw signals, levels, tables, or volume. It resolves the counterpart of the current chart symbol and transports that symbol to a receiving indicator.
█ HOW IT WORKS
The Mapper checks user supplied Symbol Mappings before its built in mappings. Each pair uses a complete TradingView ticker ID on both sides in this form:
TRADENATION:NVDA.EX = NASDAQ:NVDA
On a supported broker chart, the Mapper returns the native TradingView symbol. On a native TradingView chart, it performs the inverse lookup and returns the first matching CFD symbol.
Pine Script cannot pass a ticker string between indicators through `input.source()`. The Mapper therefore encodes the resolved ticker into two hidden numeric plots named 1st code and 2nd code . A compatible receiving indicator reads both plots and reconstructs the symbol.
█ HOW TO USE
1 — Add SVKO CFD Symbol Mapper to the chart.
2 — Add any required custom pairs to Symbol Mappings .
3 — Add a compatible receiving indicator.
4 — In that indicator, select Map: 1st code for its 1st code input and Map: 2nd code for its 2nd code input. Both selections must come from the same Mapper instance.
The Mapper remains visually silent after connection.
█ MAPPING BEHAVIOUR
Custom mappings take priority in both directions. If several CFD symbols point to the same native symbol, inverse lookup returns the first pair in mapping order.
Delayed native exchange suffixes _DL and _DLY are normalised before lookup. If no mapping exists, both code plots return zero.
The Mapper transports symbol identity only. It does not request price, volume, fundamentals, or other data from the resolved symbol.
█ LIMITATIONS
The transported ticker can contain at most 18 encoded characters. Supported characters are uppercase letters, digits, dash, colon, dot, and underscore. Unsupported characters produce a runtime error.
The receiving indicator is responsible for requesting and interpreting data from the transported symbol.
█ CREDITS AND LICENCE
Original work by SVKO. Published open source under the Mozilla Public License 2.0. Indikator

Indikator

Professional Anchored VWAP with Multi Level Standard Bands
一、指标概述
本指标是一款基于成交量加权的进阶量化分析工具,核心功能是将 VWAP 的计算起点“锚定”到您自行选择的任意历史时间点,并围绕该基准自动生成六级标准差概率通道(±0.5σ、±1.0σ、±1.5σ、±2.0σ、±2.5σ、±3.0σ),形成完整的市场价格分布监测体系。
与每日开盘重置的传统 VWAP 不同,锚定 VWAP 将计算起点固定在某个具有战略意义的时间节点——例如重大宏观事件(FOMC 决议、CPI 发布)、公司基本面事件(财报披露)、技术结构节点(趋势起点、摆动高点/低点、突破点)或任何您认为值得跟踪的时点。这种设计让您能够持续追踪“自该事件发生以来,市场真正的平均成本”,从而更精准地识别机构级支撑阻力、评估趋势健康度、捕捉均值回归机会。
本指标适用于股票、ETF、期货、加密货币等所有具备真实成交量数据的品种,并且可加载于任意时间框架(1分钟、5分钟、日线、周线等)。
二、核心理念与设计逻辑
从每日重置到事件锚定的升级
传统 VWAP 在每个交易日开盘时重新计算,对日内交易者非常实用,但对于持仓数日、数周甚至更长的波段或趋势交易者,每日重置意味着关键历史参考的丢失。AVWAP 通过固定锚点,解决了这一局限,让您能够以特定事件为原点,持续衡量市场参与者的平均成本变化。
从价格位置到统计概率的跃迁
单一的 VWAP 线只能告诉您价格在基准线上方还是下方,而本指标引入“成交量加权标准差”,将价格偏离转化为具有统计意义的概率度量。±1σ 通道覆盖约 68% 的价格分布,定义常态波动区间;±2σ 通道覆盖约 95%,反映显著偏离;±3σ 通道覆盖约 99.7%,触及此区域通常意味着极端情绪定价,均值回归的概率显著升高。这使得价格分析从“高低判断”升级为“价格在统计分布中的位置判断”,为决策提供可量化的概率依据。
三、计算方法简述
AVWAP 的计算采用典型价格(即最高价、最低价、收盘价的算术平均值)与成交量的乘积进行累加,再除以累计成交量,得到自锚点以来的成交量加权平均价格。标准差则基于价格平方与成交量的加权累加,结合方差公式 E(P²)‑E(P)² 计算得出,整个过程仅需单次数据遍历,确保在大时间窗口下的计算效率。各通道带即为 AVWAP 数值加上或减去对应倍数(0.5、1.0、1.5、2.0、2.5、3.0)的标准差值。
四、实战应用指南
趋势方向判断
当价格持续运行于 AVWAP 上方,表明自锚点以来多头占据主导,市场平均成本低于现价,多头持仓整体盈利;反之,价格持续运行于 AVWAP 下方,则空头占据主导。若价格频繁穿越 AVWAP,则市场处于震荡均衡状态。
动态支撑与阻力
AVWAP 线本身是最重要的动态支撑/阻力位。上升趋势中,价格回踩 AVWAP 并获得支撑,往往是趋势延续的信号;下降趋势中,价格反弹至 AVWAP 并遇阻,往往意味着趋势延续。各标准差通道带同样构成次级支撑/阻力区域,可作为分批建仓或止盈的参考位置。
均值回归交易
当价格延伸至外层通道(如 ±2.5σ 或 ±3.0σ)时,价格已显著偏离成交量加权公允值,历史上表现出强烈的回归倾向。触及上轨极端区域可考虑短线做空或获利了结;触及下轨极端区域可考虑短线做多或回补仓位。需注意,在强单边趋势中,价格可能在极端区域停留较长时间,建议结合其他趋势指标进行过滤。
趋势延续确认
价格在突破 +1σ 上轨后持续运行于该通道之上,并伴随成交量放大,确认强势多头趋势;反之,价格跌破 -1σ 下轨后持续运行于下方并放量,确认强势空头趋势。
多时间框架共振
建议在日线级别确定主要锚点和长期趋势方向,在小时或分钟级别寻找精确入场时机。当短周期 AVWAP 与长周期 AVWAP 方向一致时,信号可靠性显著增强。
五、锚点选择建议
良好的锚点选择是 AVWAP 有效性的前提。以下为推荐的锚点类型及示例:
宏观事件型:适用于重大政策或数据发布后的市场重定价,例如 FOMC 决议日、CPI 或非农数据发布日。
公司事件型:适用于基本面催化剂后的趋势跟踪,例如财报发布日、并购公告日。
技术结构型:适用于趋势跟踪与结构分析,例如显著摆动高点/低点、趋势起点、关键突破点。
时间节点型:适用于周期性基准参考,例如年初、月初、周初。
核心原则:锚点应选择对标的资产具有显著价格影响且市场参与者广泛关注的时间节点。
六、参数配置说明
您可以通过以下输入参数灵活控制指标显示:
锚定日期:分别设置年、月、日(默认为 2024 年 9 月 24 日)。
显示控制:您可以选择独立开启或关闭每一级标准差通道(±0.5σ、±1.0σ、±1.5σ、±2.0σ、±2.5σ、±3.0σ),按需保持图表简洁。
颜色编码体系:
蓝色基准线:AVWAP 主参考线。
绿色通道(±0.5σ、±1.0σ):常态波动区间。
橙色通道(±1.5σ、±2.0σ):中等级别偏离区间。
红色通道(±2.5σ、±3.0σ):极端偏离 / 均值回归关注区间。
七、适用交易者类型
- 日内交易者:可将锚点设为当日开盘,利用 AVWAP 作为日内公允值参考与均值回归信号。
- 波段交易者:将锚点设为关键事件或摆动点,识别中期支撑/阻力区域。
- 趋势交易者:将锚点设为趋势起点,持续跟踪趋势健康度与方向。
- 机构与专业交易者:追踪市场平均成本,识别机构级买卖区域。
八、注意事项与风险提示
- 成交量数据质量直接影响 AVWAP 的参考价值,在低流动性品种上建议谨慎使用。
- 锚点选择必须基于合理逻辑(如重大事件),随机选取的日期可能导致指标失去参考意义。
- 标准差通道基于历史数据计算,不构成对未来走势的确定性预测,通道边界是概率参考而非硬性边界。
- 均值回归策略在强劲单边市场中可能面临较大风险,建议结合趋势强度指标进行过滤。
- 本指标仅供技术分析参考,所有交易决策应由您独立判断并自行承担风险。
九、开源说明
本指标以开源方式发布在 TradingView 社区。所有代码均可供您审阅、验证功能逻辑,并基于自身需求进行修改与优化。欢迎在评论区分享使用心得、改进建议或问题反馈。
价格告诉你发生了什么,成交量告诉你谁在推动它,AVWAP 告诉你市场的真实成本在哪里。
1. Indicator Overview
This indicator is an advanced quantitative analysis tool based on volume weighting. Its core functionality is to anchor the starting point of VWAP calculation to any historical timestamp you choose, and automatically generate six levels of standard deviation probability bands (±0.5σ, ±1.0σ, ±1.5σ, ±2.0σ, ±2.5σ, ±3.0σ) around that benchmark, forming a complete market price distribution monitoring system.
Unlike the traditional VWAP which resets at the open of each trading day, the Anchored VWAP fixes the calculation origin at a strategically significant point in time – for example, major macroeconomic events (FOMC decisions, CPI releases), company‑specific events (earnings announcements), technical structure nodes (trend starts, swing highs/lows, breakout points), or any moment you consider worth tracking. This design allows you to continuously monitor "the true average cost of the market since that event occurred," enabling more precise identification of institutional support/resistance, assessment of trend health, and capturing mean‑reversion opportunities.
This indicator is suitable for all instruments with genuine volume data, including stocks, ETFs, futures, cryptocurrencies, and can be applied on any timeframe (1‑minute, 5‑minute, daily, weekly, etc.).
2. Core Concepts & Design Logic
Upgrade from Daily Reset to Event Anchoring
Traditional VWAP recalculates at the open of each trading day, which is highly useful for intraday traders. However, for swing or trend traders who hold positions for days, weeks, or longer, the daily reset means the loss of critical historical context. AVWAP overcomes this limitation by fixing the anchor, allowing you to measure the evolution of market participants’ average cost from a specific event onwards.
From Price Position to Statistical Probability
A single VWAP line only tells you whether price is above or below the benchmark. This indicator introduces "volume‑weighted standard deviation," converting price deviations into statistically meaningful probability measures. The ±1σ band covers approximately 68% of the price distribution, defining the normal fluctuation range; ±2σ covers about 95%, reflecting significant deviations; ±3σ covers about 99.7%, and touches at this level typically indicate extreme sentiment pricing, with mean‑reversion probability rising markedly. This elevates price analysis from a simple "high/low" judgment to a "position within the statistical distribution" framework, providing quantifiable probabilistic grounds for decision‑making.
3. Brief Calculation Methodology
AVWAP is computed by accumulating the product of the typical price (arithmetic average of high, low, and close) and volume, then dividing by the cumulative volume to obtain the volume‑weighted average price since the anchor. The standard deviation is derived from the volume‑weighted accumulation of squared prices, combined with the variance formula E(P²)‑E(P)². The entire process requires only a single pass through the data, ensuring computational efficiency even over large time windows. Each band is simply the AVWAP value plus or minus the corresponding multiple (0.5, 1.0, 1.5, 2.0, 2.5, 3.0) of the standard deviation.
4. Practical Application Guide
Trend Direction Bias
When price consistently trades above AVWAP, it indicates that bulls have been dominant since the anchor, as the average market cost is below the current price and long positions are in profit. Conversely, sustained trading below AVWAP suggests bearish dominance. Frequent crossovers of AVWAP imply a range‑bound/equilibrium state.
Dynamic Support & Resistance
The AVWAP line itself is the most important dynamic support/resistance level. In an uptrend, a pullback that finds support at AVWAP often signals trend continuation; in a downtrend, a bounce that meets resistance at AVWAP also indicates continuation. The standard deviation bands also serve as secondary support/resistance zones, useful for scaling entries or taking partial profits.
Mean‑Reversion Trading
When price extends to the outer bands (e.g., ±2.5σ or ±3.0σ), it has significantly deviated from the volume‑weighted fair value, historically exhibiting a strong tendency to revert. Touching the upper extreme zone may be considered for short‑term selling or profit‑taking; touching the lower extreme zone may suggest short‑term buying or covering shorts. Note that in strong trending markets, price may linger in extreme zones for extended periods; it is advisable to combine with other trend‑strength filters.
Trend Continuation Confirmation
If price breaks above the +1σ upper band and continues trading above it with rising volume, it confirms a strong bullish trend. Conversely, if price breaks below the -1σ lower band and continues below it with volume expansion, it confirms a strong bearish trend.
Multi‑Timeframe Confluence
It is recommended to determine the primary anchor and longer‑term trend direction on the daily chart, and then seek precise entry signals on hourly or minute charts. When the shorter‑timeframe AVWAP aligns with the longer‑timeframe AVWAP, signal reliability increases significantly.
5. Anchor Selection Recommendations
Proper anchor selection is a prerequisite for AVWAP effectiveness. Below are recommended anchor types with examples:
Macro‑Event Type: Suitable for market re‑pricing after major policy/data releases, e.g., FOMC decision days, CPI or Non‑Farm Payroll release days.
Company‑Event Type: Suitable for trend following after fundamental catalysts, e.g., earnings release days, M&A announcement days.
Technical‑Structure Type: Suitable for trend‑following and structural analysis, e.g., significant swing highs/lows, trend starting points, key breakout levels.
Time‑Based Type: Suitable for periodic benchmark references, e.g., start of the year, month, or week.
Core Principle: The anchor should be chosen at a point in time that had a notable price impact on the asset and is widely observed by market participants.
6. Input Parameter Settings
You can flexibly control the indicator display with the following inputs:
Anchor Date: Set year, month, and day separately (default is 2024‑09‑24).
Display Controls: You can independently enable or disable each standard deviation band (±0.5σ, ±1.0σ, ±1.5σ, ±2.0σ, ±2.5σ, ±3.0σ) to keep your chart as clean as needed.
Color Coding System:
Blue baseline: AVWAP main reference line.
Green bands (±0.5σ, ±1.0σ): Normal fluctuation range.
Orange bands (±1.5σ, ±2.0σ): Moderate deviation range.
Red bands (±2.5σ, ±3.0σ): Extreme deviation / mean‑reversion focus zone.
7. Suitable Trader Types
- Day traders: Can set the anchor to the day's open, using AVWAP as an intraday fair‑value reference and mean‑reversion signal.
- Swing traders: Anchor to key events or swing points to identify intermediate support/resistance areas.
- Trend traders: Anchor to the trend’s starting point to continuously monitor trend health and direction.
- Institutional / professional traders: Track the average market cost to identify institutional‑grade accumulation/distribution zones.
8. Important Notes & Risk Disclaimers
- The quality of volume data directly affects the reference value of AVWAP; use with caution on low‑liquidity instruments.
- Anchor selection must be based on sound logic (e.g., significant events); randomly chosen dates may render the indicator meaningless.
- Standard deviation bands are computed from historical data and do not constitute a deterministic prediction of future price movements; band boundaries are probabilistic references, not hard edges.
- Mean‑reversion strategies carry higher risk in strong trending markets; it is advisable to incorporate trend‑strength filters.
- This indicator is for technical analysis reference only. All trading decisions should be made independently by the user, who bears full responsibility for their actions.
9. Open Source Statement
This indicator is published as open source in the TradingView community. All code is available for you to review, verify its functional logic, and modify or optimise according to your own needs. Feedback, usage experiences, and suggestions for improvement are warmly welcomed in the comments section.
*“Price tells you what happened, volume tells you who is driving it, and AVWAP tells you where the market’s true cost lies.”*
Indikator

Indikator

Sprung Ladder Signals v1//@version=6
indicator("Sprung Ladder Signals v1", "SLS", overlay=true)
// ---------- Inputs (set from the gear icon, no code edits needed) ----------
shelf = input.float(0.0, "Sprung Ladder shelf level (0 = off)")
springWindow = input.int(3, "Spring reclaim window (bars)", minval=1)
lvl1 = input.float(0.0, "Alert level 1 (0 = off)")
lvl2 = input.float(0.0, "Alert level 2 (0 = off)")
hlLen = input.int(2, "Higher-low pivot strength", minval=1)
hiLen = input.int(20, "Session-high lookback (bars)", minval=5)
// ---------- Webhook payload helper ----------
f_fire(ev) =>
alert('{"event":"' + ev + '","symbol":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","price":' + str.tostring(close) + ',"t":' + str.tostring(timenow) + '}', alert.freq_once_per_bar_close)
// ---------- SWEEP: pokes below a defended shelf, closes back above ----------
sweep = shelf > 0 and low < shelf and close > shelf
var float sweepHigh = na
var int sweepBar = na
if sweep
sweepHigh := high
sweepBar := bar_index
// ---------- ta.* calls hoisted to globals so they run every bar (fixes CW10002) ----------
crossSweepHigh = ta.crossover(close, sweepHigh)
pl = ta.pivotlow(low, hlLen, hlLen)
recentHigh = ta.highest(high, hiLen)
crossRecent = ta.crossover(close, recentHigh)
crossLvl1 = ta.cross(close, lvl1)
crossLvl2 = ta.cross(close, lvl2)
// ---------- SPRING: reclaim of the sweep bar's high within the window ----------
spring = not na(sweepBar) and (bar_index - sweepBar) <= springWindow and crossSweepHigh
if spring
sweepBar := na
// ---------- HL_RECLAIM: shallow pullback holds above prior pivot low, breaks recent high ----------
var float lastPivotLow = na
if not na(pl)
lastPivotLow := pl
hlReclaim = not na(lastPivotLow) and low > lastPivotLow and crossRecent
// ---------- Visuals ----------
plotshape(sweep, "SWEEP", shape.triangleup, location.belowbar, color.orange, size=size.small)
plotshape(spring, "SPRING", shape.labelup, location.belowbar, color.green, size=size.small)
plotshape(hlReclaim, "HL_RECLAIM", shape.diamond, location.belowbar, color.aqua, size=size.tiny)
plot(shelf > 0 ? shelf : na, "Shelf", color.new(color.yellow, 30), 2, plot.style_linebr)
// ---------- Fire webhooks (one TV alert: 'Any alert() function call') ----------
if sweep
f_fire("SWEEP")
if spring
f_fire("SPRING")
if hlReclaim
f_fire("HL_RECLAIM")
if lvl1 > 0 and crossLvl1
f_fire("LEVEL1_HIT")
if lvl2 > 0 and crossLvl2
f_fire("LEVEL2_HIT") Indikator

Improved Options Confluence RSI Filter Backtest StrategyBest Settings
EMA -9
Chandlier Exit -10
Multiplier -3
Bos look back 1
For call entries RSI must be above -47
For put entries RSI must be below - 35
RSI Mid zone low 35
RSI Mid Zone High 47
Options Confluence + RSI Filter — Backtest Strategy
A multi-factor confluence strategy designed for intraday options trading (CALL/PUT), combining trend, momentum, and volatility-exhaustion filters to reduce false signals during sideways/choppy price action.
Core Logic
The strategy only enters a trade when all of the following align:
EMA (13) — price must be trading above/below the EMA in the direction of the trade
VWAP — price must also be above/below VWAP, confirming intraday value-area bias
Chandelier Exit — an ATR-based trend/volatility filter must confirm the same directional bias
Break of Structure (BOS) — price must break the recent swing high/low over a configurable lookback, confirming momentum
RSI Filter (added to reduce sideways whipsaws)
Three additional RSI-based conditions are layered on top of the core confluence:
Mid-zone block — entries are disabled entirely when RSI sits between 45-55, since this range is typically a sign of indecisive, range-bound price action with no real momentum.
Directional confirmation — CALL entries require RSI above 55; PUT entries require RSI below 45, ensuring momentum genuinely supports the trade direction.
Overbought/Oversold block — CALL entries are disabled when RSI is above 70 (overbought), and PUT entries are disabled when RSI is below 30 (oversold), avoiding entries into an already-extended move that's prone to mean-reversion.
Effectively, this narrows valid entries to two RSI bands: CALLs only between RSI 55-70, and PUTs only between RSI 30-45.
Exit Logic
Positions are closed when price crosses back below/above the EMA, or when the Chandelier Exit flips direction — whichever comes first.
Visual Aids
EMA and VWAP plotted on the price chart
Background highlighting for RSI mid-zone (sideways), overbought, and oversold conditions, so you can visually see why a trade was or wasn't taken
CALL/PUT/EXIT labels marked directly on the chart
Inputs (fully adjustable)
EMA length, Chandelier ATR period & multiplier, BOS lookback, RSI length, RSI bull/bear confirmation levels, RSI mid-zone bounds, RSI overbought/oversold levels — every filter can be toggled or tuned to fit different instruments and timeframes.
Intended Use
Built and tested on 5-minute index charts (e.g. Bank Nifty) for options directional trading. Best used as a decision-support tool alongside price action and option-chain context, not as a fully automated signal generator. As with any strategy, backtest thoroughly on your instrument and timeframe before live use, and note that past performance does not guarantee future results. Strategi

Live Price Pro Candle Timer & SL/TP DistanceThis indicator provides a clean, customizable information panel directly on your TradingView chart. It displays the current market price, the remaining time before the active candle closes, and the live distance from the current market price to your Entry, Take Profit, and Stop Loss levels.
It is especially useful for traders who want to monitor their trade levels without repeatedly calculating price distance manually.
Main features
Live market price display
Real-time countdown to candle close
Manual Entry, Take Profit, and Stop Loss inputs
Automatic distance calculation from the current market price
Distance display in:
Price
Points
Percentage
Price and points
Price and percentage
Bullish and bearish price colors
Dark or Bull/Bear background mode
Adjustable panel size
Full panel positioning across the chart
How to use the indicator
After adding the indicator to your chart, open the indicator settings.
Under Trade Levels, enter your planned:
Entry Price
Take Profit Price
Stop Loss Price
The panel will automatically calculate the distance between the current market price and each level.
For example:
Current Price: 4069.17
Entry: 4065.00
Distance: -4.17
Take Profit: 4080.00
Distance: +10.83
Stop Loss: 4060.00
Distance: -9.17
A positive value means the level is above the current market price. A negative value means the level is below the current market price.
Candle countdown
The candle timer shows the remaining time before the current candle closes.
The timer automatically adapts to the selected chart timeframe. For example:
On a 5-minute chart, it counts down to the next 5-minute candle.
On a 1-hour chart, it counts down to the next hourly candle.
On higher timeframes, it can display hours or days when required.
The timer uses the actual candle closing time provided by TradingView.
Distance modes
You can choose how the distance is displayed.
Price
Shows the direct price difference.
+10.83
Points
Shows the distance in minimum tick increments based on the symbol.
+1083 pts
Percentage
Shows the percentage difference from the current market price.
+0.27%
Price + Points
Shows both the price difference and point distance.
+10.83 | +1083 pts
Price + Percentage
Shows both the price difference and percentage distance.
+10.83 | +0.27%
Panel positioning
The panel can be placed in any of the following chart positions:
Top Left
Top Center
Top Right
Middle Left
Middle Center
Middle Right
Bottom Left
Bottom Center
Bottom Right
This allows the panel to be positioned away from candles, indicators, or other chart elements.
Customization
Users can customize:
Panel position
Panel size
Background mode
Background transparency
Bullish price color
Bearish price color
Entry color
Take Profit color
Stop Loss color
Timer and text color
Which panel rows are visible
Important notes
The Entry, Take Profit, and Stop Loss levels are entered manually. The indicator does not place, manage, or execute trades.
A value of 0 means that the selected trade level has not been configured.
Point values depend on the symbol’s minimum tick size. Therefore, the meaning of “points” may differ between gold, forex, indices, cryptocurrencies, and other markets.
The live price is based on the current chart price and may differ slightly from the executable bid or ask price shown by a broker.
Suitable for
This indicator can be used for:
Gold trading
Forex trading
Indices
Cryptocurrencies
Intraday trading
Scalping
Swing trading
Manual trade planning
Risk and target monitoring
Disclaimer
This indicator is intended for informational and educational purposes only. It does not provide financial advice, trade signals, or guaranteed results. Traders remain fully responsible for their own entries, exits, position sizing, and risk management. Indikator

Strategi

Percentage Risk Position Sizer (Bull/Bear Switch)Perfect for Prop Traders
Percentage Risk Position Sizer (Bull/Bear Switch)
An advanced, highly practical position sizing tool built specifically for day traders and futures traders who manage risk dynamically based on percentage allocation.
Customizable Multipliers: Supports configurable contract/tick multipliers for instruments like MNQ, NQ, MES, and ES.
Key Features:
Percentage-Based Risk Allocation: Easily switch between risk levels (e.g., 0.5%, 1%, 2%) tailored to your exact account size.
Automatic Candle High/Low Stop Loss: Instantly calculates risk parameters using the current candle's bottom (for Longs) or top (for Shorts).
Bull/Bear Toggle Switch: Simple input setting to flip between Buy (Bullish) and Sell (Bearish) modes instantly.
On-Chart Visuals & Labeling: Plots an extended stop loss line with a clean position size label positioned cleanly to the right to avoid chart clutter.
Real-Time Data Table: Displays total risk amount, exact position size, current stop loss level, and point distance directly in a clean top-right display table.
Inputs:
Trade Direction: Choose between Bullish (Long) and Bearish (Short).
Risk Percentage (%): Select your targeted risk per trade.
Account Size ($): Input your total account equity.
Contract/Tick Multiplier: Set your dollar value per point or tick.
Label Bar Offset: Adjust horizontal shifting to keep your live price bars completely unblocked. Indikator

Pocket Pivot (Kacher/Morales) - Customsdasd//@version=6
indicator("Pocket Pivot (Kacher/Morales) - Custom", overlay=true)
// ─────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────
smaLength = input.int(
10,
title="SMA Length",
minval=1
)
maxOffset = input.float(
4.0,
title="Max % Offset from SMA",
minval=0.1,
step=0.1
)
lookback = input.int(
10,
title="Lookback Period (Trading Days)",
minval=1
)
// ─────────────────────────────────────
// SMA
// ─────────────────────────────────────
smaValue = ta.sma(close, smaLength)
// ─────────────────────────────────────
// BUY / SELL VOLUME
// Approximation:
// Bullish candle = Buy Volume
// Bearish candle = Sell Volume
// ─────────────────────────────────────
buyVolume = close > open ? volume : 0.0
sellVolume = close < open ? volume : 0.0
// ─────────────────────────────────────
// HIGHEST SELL VOLUME
// Previous 10 candles only
// Current candle is NOT included
// ─────────────────────────────────────
highestSellVolume = ta.highest(
sellVolume ,
lookback
)
// ─────────────────────────────────────
// PRICE DISTANCE FROM SMA
// ─────────────────────────────────────
percentOffset = math.abs(
close - smaValue
) / smaValue * 100
// Price is close enough to SMA
priceNearSMA = percentOffset <= maxOffset
// ─────────────────────────────────────
// POCKET PIVOT CONDITION
// ─────────────────────────────────────
volumeCondition = buyVolume > highestSellVolume
pocketPivot = volumeCondition and priceNearSMA
// ─────────────────────────────────────
// PLOT SMA
// ─────────────────────────────────────
plot(
smaValue,
title="SMA",
color=color.teal,
linewidth=2
)
// ─────────────────────────────────────
// MARK POCKET PIVOT
// ─────────────────────────────────────
plotshape(
pocketPivot,
title="Pocket Pivot",
style=shape.labelup,
location=location.belowbar,
color=color.green,
text="PP",
textcolor=color.white,
size=size.small
)
// ─────────────────────────────────────
// ALERT
// ─────────────────────────────────────
alertcondition(
pocketPivot,
title="Pocket Pivot Detected",
message="Pocket Pivot detected on {{ticker}}"
)//@version=6
indicator("Pocket Pivot (Kacher/Morales) - Custom", overlay=true)
// ─────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────
smaLength = input.int(
10,
title="SMA Length",
minval=1
)
maxOffset = input.float(
4.0,
title="Max % Offset from SMA",
minval=0.1,
step=0.1
)
lookback = input.int(
10,
title="Lookback Period (Trading Days)",
minval=1
)
// ─────────────────────────────────────
// SMA
// ─────────────────────────────────────
smaValue = ta.sma(close, smaLength)
// ─────────────────────────────────────
// BUY / SELL VOLUME
// Approximation:
// Bullish candle = Buy Volume
// Bearish candle = Sell Volume
// ─────────────────────────────────────
buyVolume = close > open ? volume : 0.0
sellVolume = close < open ? volume : 0.0
// ─────────────────────────────────────
// HIGHEST SELL VOLUME
// Previous 10 candles only
// Current candle is NOT included
// ─────────────────────────────────────
highestSellVolume = ta.highest(
sellVolume ,
lookback
)
// ─────────────────────────────────────
// PRICE DISTANCE FROM SMA
// ─────────────────────────────────────
percentOffset = math.abs(
close - smaValue
) / smaValue * 100
// Price is close enough to SMA
priceNearSMA = percentOffset <= maxOffset
// ─────────────────────────────────────
// POCKET PIVOT CONDITION
// ─────────────────────────────────────
volumeCondition = buyVolume > highestSellVolume
pocketPivot = volumeCondition and priceNearSMA
// ─────────────────────────────────────
// PLOT SMA
// ─────────────────────────────────────
plot(
smaValue,
title="SMA",
color=color.teal,
linewidth=2
)
// ─────────────────────────────────────
// MARK POCKET PIVOT
// ─────────────────────────────────────
plotshape(
pocketPivot,
title="Pocket Pivot",
style=shape.labelup,
location=location.belowbar,
color=color.green,
text="PP",
textcolor=color.white,
size=size.small
)
// ─────────────────────────────────────
// ALERT
// ─────────────────────────────────────
alertcondition(
pocketPivot,
title="Pocket Pivot Detected",
message="Pocket Pivot detected on {{ticker}}"
) Indikator

Indikator

RS Line vs QQQ + Gap Finder// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © jacksonwarrenfenton
//@version=6
indicator("RS Line vs QQQ + Gap Finder", overlay=true, max_bars_back=5000, max_boxes_count=500)
// ─────────────────────────────────────────────
// RS LINE INPUTS
// ─────────────────────────────────────────────
displayRSData = input.bool(true, "Show RS Line", group="RS Line")
benchmarkSymbol = input.symbol("QQQ", "Benchmark ETF", group="RS Line")
iOffset = input.float(1.0, "RS Vertical Offset / Multiplier", step=0.01, group="RS Line")
iWidth = input.int(2, "RS Line Width", minval=1, maxval=5, group="RS Line")
ratioColor = input.color(color.blue, "RS Line Color", group="RS Line")
showRSDots = input.bool(true, "Show RS New High Circles", group="RS New High Signals")
// ─────────────────────────────────────────────
// RS LINE CALCULATION
// Stock you are on vs QQQ
// ─────────────────────────────────────────────
benchmarkClose = request.security(benchmarkSymbol, timeframe.period, close)
ratio = close / benchmarkClose
rsPlot = ratio * iOffset
// ─────────────────────────────────────────────
// RS NEW HIGH SIGNALS
// Daily chart: new 63-day RS high
// Weekly chart: new 12-week RS high
// These are independent from each other.
// ─────────────────────────────────────────────
isDailyRSNewHigh = timeframe.isdaily and ratio > ta.highest(ratio , 63)
isWeeklyRSNewHigh = timeframe.isweekly and ratio > ta.highest(ratio , 12)
rsNewHighSignal = isDailyRSNewHigh or isWeeklyRSNewHigh
// ─────────────────────────────────────────────
// PLOT RS LINE + BLUE CIRCLES
// ─────────────────────────────────────────────
plot(displayRSData ? rsPlot : na, color=ratioColor, linewidth=iWidth, title="RS Line")
plotshape(
showRSDots and displayRSData and rsNewHighSignal ? rsPlot : na,
title="RS New High Circle",
style=shape.circle,
location=location.absolute,
color=color.blue,
size=size.tiny
)
// =====================================================
// ============ SUPPORT/RESISTANCE GAP ZONES ===========
// =====================================================
supportColor = input.color(color.new(color.green, 88), "Support Zone Color (tested)", group="Gap Zones")
resistColor = input.color(color.new(color.red, 88), "Resistance Zone Color (tested)", group="Gap Zones")
untestedColor = input.color(color.new(color.gray, 70), "Untested Gap Color", group="Gap Zones")
borderColor = input.color(color.new(color.gray, 40), "Zone Border Color", group="Gap Zones")
limitVisible = input.bool(true, "Only show most recent zones per side", group="Gap Zones")
zonesPerSide = input.int(2, "Zones per side to show", minval=1, maxval=10, group="Gap Zones")
minGapPct = input.float(0.25, "Min Gap Size (% of price)", minval=0.0, step=0.05, group="Gap Zones")
//=====================================================
// ONE GAP DEFINITION, CLOSE-TO-LOW / CLOSE-TO-HIGH:
// Gap up (support): low > close -> zone [close .. low]
// Gap down (resistance): high < close -> zone [high .. close ]
// Must be at least minGapPct % of price.
//
// LIFECYCLE:
// Every gap SHOWS IMMEDIATELY, drawn GREY (untested) for BOTH support
// and resistance. Every day, regardless of tested status, while close
// is still within the zone's bounds:
// SHRINK: a close inside the zone pulls the near edge to that close
// (tightens only, never widens) -- higher closes eat into
// resistance from below, lower closes eat into support from
// above, whether or not the zone has been tested yet
// REMOVE: a close fully through the far edge deletes it
// Once close moves beyond the zone WITHOUT triggering removal (e.g. a
// support zone's top gets closed above without the bottom ever being
// broken), the zone simply stops updating -- it does not chase price.
// The ONLY thing "tested" controls is COLOR: once a LATER bar's wick
// tests back into the zone -- low <= top for support, high >= bottom
// for resistance -- it turns into a "drendel" gap and switches from
// grey to green/red. Shrink/remove behavior is identical before and
// after that switch.
//
// All detection/lifecycle runs on CONFIRMED bars only -- live intrabar
// prices never create, test, shrink, or delete anything.
//=====================================================
var box gaps = array.new_box()
var float tops = array.new_float()
var float bottoms = array.new_float()
var bool isSupport = array.new_bool()
var int gapKey = array.new_int()
var bool tested = array.new_bool() // false = grey/untested, true = drendel (green/red)
var int createdBar = array.new_int()
//=====================================================
// DETECTION (confirmed bars only)
//=====================================================
gapUp = barstate.isconfirmed and low > close and close != 0 and (low - close ) / close * 100 >= minGapPct
gapDown = barstate.isconfirmed and high < close and close != 0 and (close - high) / close * 100 >= minGapPct
if bar_index > 0
if gapUp
array.push(gaps, na)
array.push(tops, low)
array.push(bottoms, close )
array.push(isSupport, true)
array.push(gapKey, bar_index)
array.push(tested, false)
array.push(createdBar, bar_index)
if gapDown
array.push(gaps, na)
array.push(tops, close )
array.push(bottoms, high)
array.push(isSupport, false)
array.push(gapKey, bar_index)
array.push(tested, false)
array.push(createdBar, bar_index)
//=====================================================
// LIFECYCLE (confirmed bars only)
//=====================================================
n = array.size(gaps)
if barstate.isconfirmed and n > 0
idx = n - 1
while idx >= 0
zTop = array.get(tops, idx)
zBot = array.get(bottoms, idx)
createdOnThisBar = array.get(gapKey, idx) == bar_index
wasTested = array.get(tested, idx)
if not createdOnThisBar
if array.get(isSupport, idx)
if close < zBot
curBox = array.get(gaps, idx)
if not na(curBox)
box.delete(curBox)
array.remove(gaps, idx)
array.remove(tops, idx)
array.remove(bottoms, idx)
array.remove(isSupport, idx)
array.remove(gapKey, idx)
array.remove(tested, idx)
array.remove(createdBar, idx)
else
if not wasTested and low <= zTop
array.set(tested, idx, true)
if close <= zTop
curTop = array.get(tops, idx)
newTop = math.max(close, zBot)
if newTop != curTop
array.set(tops, idx, newTop)
curBox2 = array.get(gaps, idx)
if not na(curBox2)
box.set_top(curBox2, newTop)
else
if close > zTop
curBox = array.get(gaps, idx)
if not na(curBox)
box.delete(curBox)
array.remove(gaps, idx)
array.remove(tops, idx)
array.remove(bottoms, idx)
array.remove(isSupport, idx)
array.remove(gapKey, idx)
array.remove(tested, idx)
array.remove(createdBar, idx)
else
if not wasTested and high >= zBot
array.set(tested, idx, true)
if close >= zBot
curBot = array.get(bottoms, idx)
newBot = math.min(close, zTop)
if newBot != curBot
array.set(bottoms, idx, newBot)
curBox2 = array.get(gaps, idx)
if not na(curBox2)
box.set_bottom(curBox2, newBot)
idx -= 1
//=====================================================
// PERFORMANCE CAP -- bounds the array size so the lifecycle/visibility
// loops never keep growing unbounded over a long price history. We only
// ever need enough tracked gaps to find the most recent `zonesPerSide`
// per side, so once the total exceeds maxTracked, the oldest entries
// (front of the array, since pushes are chronological) get dropped.
//=====================================================
maxTracked = 50
n4 = array.size(gaps)
while n4 > maxTracked
oldBox = array.get(gaps, 0)
if not na(oldBox)
box.delete(oldBox)
array.remove(gaps, 0)
array.remove(tops, 0)
array.remove(bottoms, 0)
array.remove(isSupport, 0)
array.remove(gapKey, 0)
array.remove(tested, 0)
array.remove(createdBar, 0)
n4 -= 1
//=====================================================
// VISIBILITY PASS -- ranks purely by recency. Arrays stay chronological
// (oldest -> newest) since zones are only ever appended, so the most
// recent zones per side are the last ones hit scanning forward. Only the
// newest `zonesPerSide` per side (default 2 + 2 = 4 total) get a box;
// hidden ones surface as visible ones fill. Boxes extend 5 bars past the
// current bar; left edges stay anchored to the zone's formation bar.
// Color is recomputed every bar so a zone flips from grey to green/red
// the moment it gets tested. This pass is the ONLY place boxes are
// created, hidden, or recolored.
//=====================================================
n3 = array.size(gaps)
if n3 > 0
supTotal = 0
resTotal = 0
for i = 0 to n3 - 1
if array.get(isSupport, i)
supTotal += 1
else
resTotal += 1
supSeen = 0
resSeen = 0
for i = 0 to n3 - 1
side = array.get(isSupport, i)
if side
supSeen += 1
else
resSeen += 1
rankFromEnd = side ? (supTotal - supSeen) : (resTotal - resSeen) // 0 = most recent
shouldShow = not limitVisible or rankFromEnd < zonesPerSide
curBox = array.get(gaps, i)
hasBox = not na(curBox)
col2 = array.get(tested, i) ? (side ? supportColor : resistColor) : untestedColor
if shouldShow and not hasBox
top2 = array.get(tops, i)
bot2 = array.get(bottoms, i)
born2 = array.get(createdBar, i)
newBox = box.new(left=born2, top=top2, right=bar_index + 5, bottom=bot2, bgcolor=col2, border_color=borderColor)
array.set(gaps, i, newBox)
else if not shouldShow and hasBox
box.delete(curBox)
array.set(gaps, i, na)
else if shouldShow and hasBox
box.set_right(curBox, bar_index + 5)
box.set_bgcolor(curBox, col2) Indikator

Indikator

Indikator
