RONBO USA Market Open PRO v1.0The RONBO USA Market Open indicator automatically marks the official opening of the U.S. stock market at 09:30 AM New York time (Eastern Time) with a vertical line on your chart.
The indicator automatically handles Daylight Saving Time (DST) and works correctly for traders anywhere in the world, regardless of their local timezone. Whether you are trading from New York, London, Amsterdam, Tokyo or Sydney, the market open will always be displayed at the correct moment.
Features
✔ Marks the official U.S. market open (09:30 ET)
✔ Automatic Daylight Saving Time (DST) adjustment
✔ Works worldwide in every local timezone
✔ Customizable line color, style and thickness
✔ Clean, lightweight and fast
✔ Perfect for price action, liquidity and opening range analysis
Recommended Timeframes
For the most accurate results, this indicator is designed to be used on intraday charts up to and including the 1-hour timeframe.
Recommended:
1 Minute
3 Minutes
5 Minutes
15 Minutes
30 Minutes
45 Minutes
1 Hour
Why not higher timeframes?
On timeframes above 1 Hour (such as 2H, 4H, Daily or Weekly), there is no candle that starts exactly at 09:30 ET. As a result, TradingView cannot place the vertical line precisely at the official market opening.
For this reason, the indicator is optimized for 1-hour charts and lower, where the market open can be אינדיקטור

אינדיקטור

Squeeze Momentum ProSqueeze Momentum Pro (SQZP) — Squeeze-Release Momentum Signals with a Full Trade-Management Shell
█ OVERVIEW
This indicator is built on LazyBear's Squeeze Momentum Indicator as its signal engine, rebuilt into a complete "signal → trade plan → performance tracking" tool. Instead of only displaying squeeze states, it turns each squeeze release into an actionable signal with a defined direction, stop-loss, and three take-profit levels — and it continuously tracks the historical performance of every signal, so you can verify for yourself whether this signal has merit on your instrument and timeframe.
█ SIGNAL LOGIC
Entry signal = squeeze-release bar + momentum direction confirmation:
• Squeeze: Bollinger Bands contract fully inside the Keltner Channel — volatility compression, energy building up.
• Release: the bar where the squeeze ends (sqzOn → off), confirmed on close.
• Direction: determined by the linreg momentum value — long when > 0, short when < 0.
• Optional quality conditions: Minimum Squeeze Bars (the squeeze must last N consecutive bars before release, filtering out shallow compressions) and Momentum Strengthening (the release bar's momentum must be stronger than the previous bar's, matching the "bright" histogram state of the original).
Changes and extensions relative to LazyBear's original:
1. The original only plots a momentum histogram and squeeze dots. This script turns the release bar into a tradable event, and adds the two quality conditions above.
2. Complete exit plan: SL anchored at entry price by ATR multiple; TP1/TP2/TP3 defined in R-multiples (multiples of the actual per-trade risk), with a one-third scale-out settlement model.
3. Trade card: the latest signal's entry, stop, and three targets displayed directly on the chart, with risk-amount conversion.
4. Performance panel: automatic tracking of win rate, profit factor, expectancy (in R), max drawdown, and an equity curve across all historical signals.
5. Edge diagnostics row: MFE/MAE and post-signal N-bar drift (with long/short breakdown and a non-overlapping sampling mode), for testing whether the entry itself carries directional information.
6. Optional filters (ADX / RSI / Volume, OFF by default) and a session filter, for running your own conditional hypothesis tests.
█ HOW TO USE
1. Add to chart. Orange dots along the bottom mark an active squeeze; a long/short marker appears on the release bar.
2. Check the trade card (top right) for the full price plan of the latest signal (entry / SL / TP1-3).
3. Open the stats panel and inspect the historical expectancy of this signal on your symbol and timeframe — if expectancy is negative or the sample is too small, do not trade it there.
4. Built-in Buy / Sell alert conditions are available for creating alerts.
The default parameters (BB 1.5×20, KC 2.0×20, min squeeze 3 bars, momentum strengthening ON, SL 3.0×ATR, TP at 2/3.5/6 R) reflect the author's offline testing preference on crypto 1H charts. Treat them as a starting point only and re-validate on your own market and timeframe. Note: a BB multiplier of 1.5 reproduces the actual behavior of LazyBear's original; the textbook 2.0 definition can be restored via the input.
█ IMPORTANT DISCLAIMERS
• The built-in performance statistics do NOT include commissions or slippage and are therefore systematically optimistic. They are intended for relative signal-quality comparison only and are not a promise of profitability.
• Historical statistics do not predict future results. Extended losing streaks can occur in any period — manage your own risk.
• This indicator is for educational and research purposes only and does not constitute investment advice.
Credits: the signal engine is derived from LazyBear's Squeeze Momentum Indicator — thanks for the open-source contribution.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Squeeze Momentum Pro(SQZP)— 擠壓釋放動量訊號 + 完整交易管理外殼
█ 這是什麼
本指標以 LazyBear 的 Squeeze Momentum Indicator 為訊號引擎基礎,重建為一套完整的「訊號 → 進出場計畫 → 績效追蹤」工具。它不只畫出擠壓狀態,而是在每次擠壓釋放時給出明確的進場方向、停損價、三段停利價,並持續統計所有歷史訊號的表現,讓你能自行檢驗這個訊號在你的商品與週期上是否有效。
█ 訊號邏輯
進場訊號 = 擠壓釋放棒 + 動量方向確認:
• 擠壓(Squeeze):Bollinger Bands 完全收進 Keltner Channel 內,代表波動壓縮、能量累積。
• 釋放(Release):擠壓狀態解除的那根 K 棒(sqzOn → off),於收盤確認進場。
• 方向:以 linreg 動量值判定 — 動量 > 0 做多、< 0 做空。
• 可選強化條件:最少擠壓棒數(釋放前需連續擠壓 N 棒,過濾淺層壓縮)、動量需增強(釋放棒動量須比前一棒更強,對齊原版直方圖的「亮色」狀態)。
相對 LazyBear 原版的修改與擴充:
1. 原版只顯示動量直方圖與擠壓點,本指標將「釋放棒」事件化為可交易訊號,並加上最少擠壓棒數與動量增強兩個品質條件。
2. 完整出場計畫:SL 以 ATR 倍數錨定進場價,TP1/TP2/TP3 以 R 倍數(實際風險的倍數)設定,支援三等分分批出場模型。
3. 交易卡:圖上直接顯示最新訊號的進場價、停損價、三段停利價與風險金額換算。
4. 績效統計表:自動追蹤所有歷史訊號的勝率、獲利因子、期望值(R)、最大回撤與資金曲線。
5. Edge 診斷列:MFE/MAE、訊號後 N 棒漂移(含多空分解、非重疊取樣模式),用於檢驗訊號本身是否含方向資訊。
6. 可選濾網(ADX / RSI / 量能,預設關閉)與 Session 時段過濾,供使用者自行做條件化檢定。
█ 使用方式
1. 掛上圖表後,圖下緣橘點表示擠壓進行中;出現多/空標記即為釋放訊號。
2. 看右上角交易卡取得該筆訊號的完整價位計畫(進場/SL/TP1-3)。
3. 打開統計表,觀察此商品此週期的歷史訊號期望值——期望值為負或樣本太少,就不要用在這個市場。
4. 內建 Buy / Sell 警報條件,可直接建立 Alert。
預設參數(BB 1.5×20、KC 2.0×20、最少擠壓 3 棒、動量需增強、SL 3.0×ATR、TP 2/3.5/6 R)為作者在加密貨幣 1H 週期上離線檢驗後的偏好配置,僅供起點參考,不同商品與週期請自行重新檢驗。註:BB 乘數 1.5 對應 LazyBear 原版的實際行為;正統 2.0 定義亦可透過參數還原。
█ 重要聲明
• 指標內建的績效統計未計入手續費與滑價,數字系統性偏樂觀,僅供訊號品質的相對比較,不構成任何獲利承諾。
• 歷史統計不代表未來表現。任何時期都可能出現連續虧損的區間,請自行做風險管理。
• 本指標為教育與研究用途,不構成投資建議。
致謝:訊號引擎源自 LazyBear 的 Squeeze Momentum Indicator,感謝其開源貢獻。 אינדיקטור

Strong Prop Challenge Sim | ProjectSyndicateStrong Challenge Sim answers the one question every prop-firm trader pays to find out the hard way: with the edge you actually have, what are the odds you pass — and what kills you when you don't. Instead of a single pass/fail formula, it runs thousands of complete evaluations trade-by-trade and day-by-day, enforcing your firm's real rule set the way the firm enforces it: profit target, daily loss limit, maximum drawdown, minimum days, deadline, and consistency. Every simulated run is counted into exactly one outcome — passed, killed by the daily limit, killed by max drawdown, voided by the consistency rule, or out of time — so the buckets always sum to 100% and no losing run is hidden. The result is drawn as real equity curves on a real balance axis in its own pane, ranked on a two-panel dashboard, priced out in expected value, and audited against a pre-flight checklist — so you can see how the challenge behaves on your numbers before you pay a fee.
🎲 Monte-Carlo Core — the core idea, expressed as a lifecycle: EDGE ▸ TRADES ▸ DAYS ▸ RULES ▸ VERDICT. Your edge is defined per trade — win rate, reward:risk, average loss in R, risk basis and size, trades per day. The engine plays that edge forward one trade at a time, accumulates each day, and after every single trade it checks the rule stack in the same order a firm's risk system does: has equity touched the maximum-drawdown floor, has the day's loss breached the daily limit, has the profit target been reached, and have the minimum trading days been served. The drawdown floor itself is modelled three ways — Static from your starting balance, Trailing from the equity peak, or Trailing → locks once the floor reaches your starting balance — because that single rule changes the answer more than almost anything else. Phase 1, Phase 2, or both back-to-back. A deterministic seed makes every result reproducible; change it to draw a different sample.
📈 Equity Simulator — the whole point is to watch the runs, so the indicator lives in its own pane on a true balance axis rather than fighting your price scale. Up to eight complete simulated challenges are drawn as full equity curves, stretched across an adjustable width, each coloured by how it actually ended: green passed, orange died on the daily loss limit, red blew the maximum drawdown, blue passed the target but was voided by the consistency rule, grey ran out of time. Every curve prints its ending balance and outcome at its right edge, and the Target, Start, and Max-DD reference lines are labelled with their real money values — so you read the balances directly instead of guessing at the scale.
🧮 Edge Analytics — the deterministic maths behind the simulation, stated plainly: expectancy per trade in R and as a percentage of equity, theoretical profit factor, break-even win rate, your margin above or below it, the Kelly-optimal risk with a verdict on the risk you actually chose (conservative / aggressive / OVER-BET), and the estimated number of trades to reach target alongside the average the simulation really needed. If the edge is negative, this is where it shows up first — no number of simulations fixes maths that doesn't work.
⚙️ Execution Reality — the section most calculators pretend doesn't exist, and the reason backtests flatter you. Two costs are modelled explicitly. Spread and slippage are charged on every single trade in R, shrinking every winner and deepening every loser, because clean mid-price backtesting overstates performance. Execution Rate captures the gap between the strategy and the operator: the share of setups you actually take by the rules, with the remainder taken as marginal, late, off-rule entries at a degraded win rate. The panel then shows your Backtest WR → Real WR and the exact R your edge loses to costs and execution. Improving execution is frequently worth more than optimising the strategy.
🧠 Loss-Streak Anchor — the psychological instrument. The engine records the longest run of consecutive losers in every simulation and reports the typical and worst streak you should expect, then converts the worst one into what it actually costs as a percentage of your account. This is the number that stops you revenge-trading on loss four when your own data says six is normal — and it is also a hard risk test: if your worst plausible streak costs more than the maximum drawdown, the challenge is unsurvivable at that risk size no matter how good the headline pass probability looks.
💰 Challenge Economics — a challenge is a purchase, so it gets priced like one. Enter the fee, whether it's refunded on first payout, your profit split, the profit you expect per payout cycle, and how many cycles you realistically expect to collect. The panel returns the expected number of attempts to pass, the total fees you should expect to spend getting there, your expected payouts, the net expected value of the whole venture, and the ROI on fees — flagged +EV or −EV. A 99% pass probability and a −EV verdict can coexist; this is where you find out.
📅 Profit Calendar — a day-by-day heat map of one sample run, up to thirty trading days, green for up days and red for down days with the intensity scaled to the size of the move and the P/L printed in each cell, plus that run's final outcome. It turns an abstract probability into a story you can read: where the drawdown hit, which day carried the account, and whether one outsized day is quietly setting up a consistency-rule violation.
⚖️ Rule-Profile Comparison — your identical edge run against six different rule sets side by side, showing target, daily limit, maximum drawdown and the resulting pass probability, with your own rules marked. Profiles are labelled by their actual numbers and drawdown type rather than by brand, because firm terms change and the rules are what the maths responds to. The same trader can be comfortably profitable under one rule set and mathematically doomed under another — this makes that visible before you choose.
🔥 Sensitivity Grid — an optional 5×5 heat grid re-running the simulation across a range of win rates and reward:risk ratios around your inputs, colour-graded by pass probability with your base case marked. It shows how fragile or robust your pass odds are: whether you sit on a plateau where a small slip still passes, or on a cliff edge where two points of win rate is the difference between funded and refunded.
✅ Readiness Checklist — the pre-flight audit, scored out of eight, every box ✓ before you pay: the edge is positive after costs, the sample behind your numbers is at least 100 trades, risk sits at or below half-Kelly, pass probability clears 50%, the worst loss streak is survivable inside the maximum drawdown, spread and slippage are actually modelled, execution rate is at least 85%, and the average drawdown per run stays inside the limit. Each item shows the value it was judged on, so a ✗ tells you exactly what to fix.
📊 Two-Panel Dashboard — the read-out is split into two panels so it fits on a normal screen. Panel A — Results carries the verdict with a pass-probability bar and a plain-language rating, the full failure breakdown by cause, time to pass as median / fastest 10% / average / slowest 10% with the average ending balance and net P/L, the loss-streak anchor, day extremes (average up day, average down day, gain/loss ratio, best and worst day), and your setup summary. Panel B — Edge & Economics carries edge analytics, execution reality, challenge economics, and the readiness checklist. Both panels, the calendar, the comparison and the grid can each be placed in any of nine screen slots at three text sizes, so nothing overlaps whatever else you run.
🎚️ Discipline & Behaviour Controls — rules you impose on yourself, tested rather than assumed. A daily profit lock stops the day after +X R; a circuit breaker stops it after −Y R. Tilt / revenge sizing models the classic killer: after a chosen number of consecutive losses, risk is multiplied — switch it on and watch the daily-loss failure rate climb. The consistency rule caps how much of total profit a single day may carry and voids passes that breach it, exactly as firms do. Variable R randomises win and loss sizes around your averages for extra realism.
🔔 Alerts — fires on a positive edge (expectancy above 0R after costs) and on a negative edge, the latter being the one that matters: it means the challenge maths does not work at your current inputs, regardless of how the curves happen to look.
🔧 Fully Customizable — every component is exposed: account size, currency symbol and phase; both profit targets, daily and maximum drawdown, drawdown type, minimum days, deadline, and the consistency rule with its threshold; win rate, reward:risk, average loss in R, risk basis (current equity / starting balance / fixed amount), risk size, trades per day, and the sample size behind your numbers; spread and slippage in R, execution rate, off-rule win rate, and tilt with its trigger and multiplier; the profit lock and circuit breaker; fee, refund, split, payout percentage and payout count; simulation count, seed, and R randomisation; curve count, curve width, reference lines and balance labels; and every panel, module, position and text size.
🎯 Why this is different — a pass-probability calculator gives you one number from a formula and stops. This runs the entire evaluation thousands of times under the firm's real rule stack, tells you not just whether you pass but precisely what kills you when you don't, charges you for spread and for the trades you don't take properly, hands you the loss streak you must be able to sit through, prices the attempt in expected value rather than hope, checks your readiness against eight objective boxes, and draws the whole thing as honest equity curves where every stop-out is counted. It is built to talk you out of a bad challenge, not into one.
🚀 Where to use it — the simulator is symbol- and timeframe-agnostic: it models your trading edge and your firm's rules, not the chart it sits on, so you can leave it on any instrument on any timeframe and the answer is the same. Load the chart you actually intend to trade for context, feed it the win rate and reward:risk from your own backtest or journal on that market, and set the rule inputs to your specific target firm — different firms' rules produce materially different answers from the identical edge.
🎯 How to use it
Enter your firm's rules exactly — target, daily limit, maximum drawdown, and above all the correct drawdown type, since Static, Trailing and Trailing → Lock are not interchangeable.
Enter your real edge from a real sample — win rate, reward:risk, average loss in R, risk per trade and trades per day — and set the sample size honestly. Under 100 trades, the checklist will flag your numbers as statistically meaningless, and it is right.
Set the execution reality before you believe anything — put your true spread and slippage in R, and set your execution rate to what you actually achieve, not what you intend. Watch Backtest WR → Real WR.
Read the verdict, then read why runs fail — the failure breakdown tells you what to fix. Daily-limit failures mean size or tilt; max-drawdown failures mean the edge or the risk; timeouts mean the target is out of reach in the time allowed.
Check the loss-streak anchor and the checklist before the pass probability — a 99% pass probability with an unsurvivable worst streak is a tail risk, not a green light.
Price it in Panel B — if the net expected value is negative, the challenge is a bad purchase however good the odds look.
Tune risk with the Kelly verdict and the sensitivity grid, and re-check the calendar for consistency-rule exposure if your firm enforces one.
⚠️ Important — this is a planning and decision-support tool, not a trading system, and it makes no performance guarantees. Every output is a probabilistic estimate derived entirely from the inputs you provide: the simulation cannot know your real edge, and garbage in is garbage out with three decimal places. Real markets are not independent coin flips — they cluster, trend, gap and change regime, while the model assumes each trade is an independent draw from your stated win rate, so treat the results as the mathematical shape of your challenge rather than a forecast of it. Pass probability is the headline and the least useful number on its own; weigh it against the failure breakdown, the loss-streak anchor, average drawdown and expected value. Rule sets vary between firms and change over time — verify every rule against your firm's current terms, particularly the drawdown type and any consistency requirement. No simulation, however honest, is a substitute for a tested edge and your own risk management. אינדיקטור

BTC Trend-Momentum Strategy A rules-based long/short strategy designed specifically for Bitcoin, combining three complementary components:
Trend filter (EMA 200): Only trades in the direction of the prevailing trend — long above the EMA, short below it.
Volume confirmation (Chaikin Money Flow): Confirms that actual buying or selling pressure supports the trend direction before entering.
Momentum trigger (Stochastic RSI): Times entries when %K crosses back out of oversold/overbought territory, avoiding entries at momentum extremes.
Optional volatility filter (ATR vs. its moving average): Can restrict trading to periods of above-average volatility, filtering out low-volatility chop.
Risk disclosure: This strategy has no built-in stop-loss or take-profit. Positions are only closed by an opposing signal (a long signal closes an existing short and vice versa). This means an open position can theoretically run at a loss for an extended period before the opposite signal triggers. Traders should manage their own risk (position sizing, stops) independently when applying this on a live account.
Backtest settings used: Initial capital $1,000, 0.075% commission per trade, no slippage, 100% equity per trade, tested on BTC/USD from 2018 onward. Past performance does not guarantee future results.
This publication is for educational purposes only and does not constitute financial advice. אסטרטגייה

Session Profitability Visualizer
What it shows
Session Profitability Visualizer breaks the trading day into its 24 hours and shows, for each hour, how price has historically behaved on your chart. It answers a simple statistical question: "When this market trades at 09:00 vs. 14:00 vs. 20:00, how have bars in that hour tended to move?"
For every hour with enough data it displays a table with:
- Hour — the hour-of-day bucket (00:00–23:00) in the symbol's exchange timezone
- Cum move — the cumulative close-minus-open of all completed bars in that hour (in points, or in % if you select the percent metric)
- Bars — how many completed bars contributed to that bucket (the sample size)
- % Pos — the share of those bars that closed above their open
Rows are tinted green or red by the sign of the cumulative move, with color intensity scaled by magnitude relative to the strongest hour, so the "heavier" hours stand out at a glance. An optional (off by default) background shading tints the chart by the historical statistics of the hour the current bar belongs to.
How it works
On every completed intraday bar inside the lookback window, the script:
1. Determines the bar's hour of day using the symbol's exchange timezone (syminfo.timezone).
2. Computes the bar's move — either close − open in points, or (close − open) / open × 100 in percent, depending on the Metric input.
3. Adds that move to the hour's running sum, increments the hour's bar count, and increments a positive-bar counter when the move is positive.
The per-hour sums, counts, and positive counts are held in three 24-element arrays. The table is rendered once on the last bar from those arrays. There is no request.security() call, no reference to future data, and only confirmed bars are counted — the statistics do not repaint on historical data (the live, still-forming bar is excluded until it closes).
Inputs
- Lookback (bars) — how many recent bars feed the statistics (default 5000). Larger windows are more stable; smaller windows react faster to regime changes.
- Metric — Points (close − open) or Percent (bar return %). Percent is more comparable across price levels and long histories.
- Min samples per hour — hours with fewer completed bars than this are hidden (default 30), so thin buckets don't masquerade as meaningful.
- Table position — where the table sits on the chart.
- Shade background — optional tint of the current bar's hour by its historical stats (off by default).
How to use it
Apply it to any intraday chart (15m or 1h are good starting points — on a 15m chart each hour bucket gets four bars per session). Look for hours where the cumulative move and the % positive rate agree and the sample count is healthy; those are the hours where the market has shown a persistent directional lean on your symbol. Compare the same symbol on different lookbacks to see whether the pattern is stable or an artifact of one period.
Limitations — please read
- Hour buckets use the symbol's exchange timezone, not your chart's display timezone. A "09:00" row on NASDAQ symbols means 09:00 America/New_York regardless of your local clock.
- Bar close-minus-open is a directional proxy, not trade P&L. It ignores spreads, slippage, position sizing, and intrabar path.
- The statistics are a historical observation, not a prediction. An hour that has drifted up for 5000 bars can stop doing so at any time; sample sizes shrink quickly on higher intraday timeframes.
- The script is intraday-only by design; on daily and above it shows an explanatory message instead of statistics.
This is a statistical visualization tool. It does not generate signals or recommendations of any kind.
אינדיקטור

Multi-Timeframe Squeeze Board LiteWhat it shows
Multi-Timeframe Squeeze Board — Lite answers one question at a glance: "Where is this symbol compressed, and which way is momentum leaning, on every timeframe that matters?" For the chart's symbol it displays a compact table with one row per timeframe — 15m, 1h, 4h, Daily, Weekly — and two readings per row:
- Sqz — the TTM Squeeze compression state as a colored dot, using the standard three-level cascade: orange = high squeeze (deepest compression), red = mid squeeze, black = low squeeze, green = no squeeze (volatility released / normal).
- Mom — the squeeze momentum oscillator as a colored arrow using the classic 4-color scheme: aqua = positive and rising, blue = positive but falling, yellow = negative but rising, red = negative and falling. The arrow points up when momentum is increasing bar-over-bar and down when it is decreasing.
A stacked squeeze (orange/red dots on several adjacent timeframes) marks a market coiling across horizons; the momentum colors tell you which side the pressure is building on.
How it works
Each row runs the full TTM Squeeze calculation on its own timeframe via request.security() with lookahead = barmerge.lookahead_off (no future data, ever):
1. Bollinger Bands: SMA(close, 20) basis, 2.0 × population standard deviation.
2. Keltner Channels: the same SMA(close, 20) basis, with band width = SMA of True Range over 20 bars (simple average of TR — not Wilder's ATR) at three multipliers: 1.0, 1.5, 2.0.
3. A squeeze is on when the Bollinger Bands sit fully inside the Keltner Channel on both sides. The narrower the Keltner band that still contains the BB, the deeper the compression — hence the 1.0-multiplier band defines the high squeeze, 1.5 the mid, 2.0 the low.
4. Momentum is the linear regression of price's deviation from the average of the Donchian midline and the SMA, over the same 20 bars.
By default the board evaluates confirmed bars only: every row shows the last fully closed bar of its timeframe, so a dot or arrow never changes after it appears. See Limitations for the tradeoff.
Inputs
- Squeeze length — lookback for BB, KC and momentum (default 20, the canonical TTM setting).
- Confirmed HTF bars only — ON (default): stable, non-repainting readings that lag up to one bar of each row's timeframe. OFF: rows track the still-forming higher-timeframe bar — more current, but the reading can flip until that bar closes.
- Table position / Table size — where the board sits and how large it renders.
How to use it
Apply it to a 15m chart (or lower) so all five rows populate. Scan the Sqz column top-to-bottom: multiple orange/red dots stacked across timeframes indicate multi-horizon compression — historically the precondition for expansion moves. Then read the Mom column for directional lean while the compression resolves. The board is a context tool: it tells you where energy is stored, not when or in which direction it must release.
Limitations — please read
- Confirmed-bar lag: with the default non-repainting mode, the Weekly row updates once per week, the Daily row once per day, etc. That is the honest cost of stability. Turning the toggle off shows the live forming bar instead, and those readings can change until the bar closes.
- Rows below the chart's timeframe show "–": Pine's request.security() cannot reliably reconstruct lower-timeframe series, so instead of showing a possibly wrong dot the board declines to show one. Use a 15m chart to see everything.
- A squeeze has no direction. Compression means stored energy, not a buy or sell signal. The momentum color is a lean, not a prediction.
- Warm-up: each timeframe needs about 20 bars of history before its row populates (shown as "·" until then).
This board covers one symbol — the chart's.
אינדיקטור

אינדיקטור

אינדיקטור

אינדיקטור

Quick Level InputsPlot levels by typing them, not by drawing them
OVERVIEW
Plot horizontal levels by typing prices instead of dragging lines. Paste a
comma-separated list, pick a color, done. Six independent groups, each
optionally bound to its own ticker, so a single instance can hold level sets
for multiple symbols and swap between them automatically as you change charts.
THE PROBLEM IT SOLVES
Drawing tools are fine until your prep produces a *list*. Pivots, prior
session highs/lows, gamma strikes, VWAP anchors — if the output of your
process is numbers, translating them into hand-dragged lines is slow and
imprecise. Typing the price is exact and takes a second.
The usual catch with a Pine-based approach is that indicator inputs aren't
tied to a symbol: switch the chart and your ES levels are sitting on NQ. This
script fixes that with per-group ticker binding.
FEATURES
• Unlimited levels per group — just type or paste "5312, 5288.5, 5250"
• 6 independent groups, each with its own color, width, style, and label text
• Per-group ticker binding — blank draws on any symbol; set a ticker and that
group only appears on that chart
• Zone shading — pair levels to shade bands for chop zones, expected pivot
ranges, or supply/demand
• Price-scale tags — levels show as colored price tags on the right axis
• Full color pickers with opacity, plus a master opacity fade for all lines
• Extend right / both / none
• Optional on-chart labels with adjustable size and bar offset
• Fails quietly — an unmarked ticker simply draws nothing
HOW TO USE
1. Add to chart and open settings.
2. In any group, type your levels into the Levels field, separated by commas:
5312, 5288.5, 5250
Semicolons work too. Spaces are ignored. Unparseable entries are skipped
rather than breaking the script.
3. Pick a color, width, and line style for that group.
4. Optional: set a Ticker to bind the group to one symbol. Leave it blank to
draw on every symbol.
Think of groups as buckets, not rows. A typical setup:
Group 1 — red, solid, width 2 → key pivots
Group 2 — blue, solid, width 1 → secondary levels
Group 3 — amber, "Solid + Zone" → expected chop zone
ZONES
Choose any "+ Zone" style and the group's levels pair up sequentially:
5340, 5325 → one shaded band
5340, 5325, 5280, 5262 → two shaded bands
Order within a pair doesn't matter (high/low is sorted for you). An odd
leftover level draws as a plain line. Fill transparency is set by "Zone fill
opacity".
MULTI-SYMBOL WORKFLOW
Set Group 1's ticker to ES1! and Group 2's to NQ1!, each with its own levels.
Flip the chart between the two symbols and the correct set appears
automatically — one indicator instance, no duplicate copies, no retyping.
Blank-ticker groups act as a "draws on everything" layer.
SETTINGS
• Show price labels (on line) — text labels riding on each level
• Show levels in price scale — colored tags on the right axis
• Label size / Label offset — offset pushes labels N bars right, clear of
price action
• Extend — Right, Both, or None
• Master opacity — fades every line at once; at 100 each group's own
color-picker opacity is used as-is
• Zone fill opacity — higher is more transparent
NOTES AND LIMITS (read these)
• Price-scale tags cover the FIRST 20 LEVELS in group order. Pine requires a
fixed number of plot() calls, so this can't be unbounded. Levels beyond 20
still draw as lines and labels normally — they just don't get an axis tag.
Zones consume two tags each (high and low).
• Color, width, and style are per GROUP, not per individual level. That's the
deliberate tradeoff for pasteable lists. Use a separate group per color.
• Levels are stored per indicator instance in your chart layout — not per
symbol in TradingView's own storage. Ticker binding controls VISIBILITY,
not storage. Save your layout to persist them.
• Drawing happens once on the last bar and objects are cleaned up on redraw,
so it stays light regardless of history length.
CREDITS
The input model here — grouped, comma-separated level strings with per-group
symbol binding, and the zone concept — is based on "Quick Levels" by
@SamRecio. This is an independent rewrite rather than a fork: it adds full
color pickers (instead of a fixed color list), price-scale tags, an extend
option, master opacity, multiple zones per group, and single-pass rendering
on the last bar; and it removes the runtime error on unmarked tickers. Credit
to SamRecio for the original design. Licensed MPL 2.0. אינדיקטור

Balanced Price Range (BPR) [TakingProphets]OVERVIEW
The Balanced Price Range (BPR) study identifies areas where two opposing fair value gaps overlap in price. It marks the shared region between an inverted fair value gap and the newly formed gap that caused the inversion, tracking these zones forward in time until they are invalidated.
PURPOSE AND SCOPE
-----------------------------------------------------------------------------------------------
This study is intended for analytical and educational use. It automates the visual identification of overlapping gap regions so that a chart reader does not need to manually measure where two opposing fair value gaps intersect.
The study does not generate trade signals, recommendations, or forecasts. All markings are analytical references only.
LOGIC STRUCTURE
-----------------------------------------------------------------------------------------------
The study first identifies standard fair value gaps.
When an existing fair value gap is inverted by a confirmed candle close through it, the study checks whether the move responsible for that inversion also formed a new fair value gap in the opposing direction.
If it did, the study calculates the overlapping price region shared by the original gap and the newly formed opposing gap. That shared region is the Balanced Price Range.
If the two gaps do not share any overlapping price, no zone is drawn.
A bullish gap inverted downward by a bearish gap produces a bearish Balanced Price Range. A bearish gap inverted upward by a bullish gap produces a bullish Balanced Price Range.
A zone is invalidated when price closes back through it against its direction. A bearish zone is invalidated on a confirmed close above the zone high. A bullish zone is invalidated on a confirmed close below the zone low. Invalidated zones are removed from the chart and are not restored.
All state transitions require a confirmed bar close. Wicks and intrabar movement do not trigger detection or invalidation.
COMPONENTS AND VISUALS
-----------------------------------------------------------------------------------------------
Balanced Price Range zones are drawn as boxes spanning the overlapping price region and extended forward in time.
Bullish and bearish zones are styled independently.
An optional gradient renders each zone in graded bands at the zero, twenty five, fifty, seventy five, and one hundred percent levels of the zone, each with independent color, style, and thickness settings.
Optional labels identify each zone as a Balanced Price Range, positioned outside the lower right of the zone, with selectable label sizes.
INPUT CATEGORIES
-----------------------------------------------------------------------------------------------
General settings control detection sensitivity, minimum zone sizing, and how many zones are displayed on the chart.
Style settings control zone colors, gradient bands, label visibility, and label sizing for bullish and bearish zones independently.
USAGE GUIDELINES
-----------------------------------------------------------------------------------------------
This study is intended as a contextual reference for observing how price interacts with regions where opposing gaps overlap.
Zones may be used as study markers for observation and journaling. They are not entries, exits, or targets.
The study is designed for use alongside a reader's own analysis rather than in isolation.
OPERATIONAL NOTES AND LIMITATIONS
-----------------------------------------------------------------------------------------------
Because the overlapping region is by definition smaller than either source gap, zones can be narrow on lower timeframes. The minimum sizing filter is provided to manage this.
Detection depends on confirmed closes, so zones appear only after the relevant candle has closed.
Historical and real time behavior may differ in appearance as bars confirm.
Past chart behavior does not indicate future behavior. This study describes structure that has already formed.
ORIGINALITY AND ATTRIBUTION
-----------------------------------------------------------------------------------------------
This implementation is original code. The underlying concepts of fair value gaps, gap inversion, and balanced price ranges are widely discussed within the trading education community and are not claimed as proprietary.
TERMS AND DISCLAIMER
-----------------------------------------------------------------------------------------------
This study is provided for educational and analytical purposes only. It does not constitute financial advice, investment advice, or a recommendation to buy or sell any instrument.
Trading involves substantial risk of loss. Any decisions made are the sole responsibility of the user. אינדיקטור

Buyers/Sellers Trapped V2This spots the bar where price spikes hard one way, then reverses and closes back against the spike. Whoever chased the move is trapped, and price usually keeps going the way it reversed.
I first published a version of this in 2017. This is the rebuild.
On the chart
*ST (green, up arrow): sellers trapped after a down spike. Bullish continuation cue.
*BT (red, down arrow): buyers trapped after an up spike. Bearish continuation cue.
*Trend filter (EMA + slope) highlights signals that line up with the trend and fades or hides the rest. The trend-aligned ones are the setups that matter.
*ATR-buffered stop just beyond the spike, so invalidation isn't sitting on the wick.
*Exit marker when the trend flips (price closes back through the MA) or the stop gives out.
How I use it
*Trade it with the trend, not against it. A trap in the direction of an established trend is a continuation entry, or a spot to add to a position you already hold.
*Stop goes an ATR beyond the spike.
Don't cap it with a tight target. The spike makes the stop wide, so a small fixed target pays you badly for the risk. Let it run and exit on the trend flip. In my own testing across crypto, riding to the trend flip beat every fixed target, and the long side carried most of the edge.
*Strongest in trending markets, noisy in chop, so lean on the trend filter. Alerts are built in for the entries, the trend-aligned entries, and the exit.
Free to use, feedback welcome.
Cheers,
Ivan Labrie. אינדיקטור

Break & Re-Test Zones v5.2 Outcome AuditHere's the full description of the indicator — what it is, what it draws, and how it thinks.
What it is
It's a TradingView indicator that automates the Break & Re-Test strategy on 15-minute Gold and NQ futures. It finds support/resistance zones by itself, watches for one to break, waits for price to come back and confirm the flip, and only then fires a buy or sell signal — with entry, stop, and targets pre-calculated. Two versions exist: the indicator (v5.1) for live trading and chart-reading, and a strategy sibling that runs the identical logic through TradingView's backtester.
What it draws — the five layers
1. Support & resistance zones. Built automatically from swing pivots, drawn as bands (not lines), and colour-coded by where price sits right now: green below price = support, red above = resistance, gray = price inside it ("IN TEST"). Each zone is also classified PRIMARY (solid thick border, likely to hold — earned by having 2 of: multiple touches, overlap with a higher-timeframe level, or a round number inside it) or SECONDARY (dashed, likely to break). White labels show the price and touch count. This is the map.
2. The armed state. When a candle body closes through a zone, that zone turns orange with a "RETEST? / ARMED" label — meaning a break happened and the indicator is now watching for the pullback. It's a watch notice, never an entry, and it lives only while the setup is genuinely armed.
3. The signal / trade package. When price returns and a confirmation candle closes back on the breakout side, the entry fires: a coloured arrow at the candle, a banner with direction and confluence grade ("LONG @ …"), plus dotted rails to the entry, a hollow-circle stop, and blue-square TP1/TP2 targets. Stop goes beyond the zone; targets sit at 1.5R and 2R.
4. The outcome audit. Every fired trade tracks itself: stopped out, the whole package erases; reaches TP1, it's immortalised as a yellow-bordered rectangle spanning the winning run. Only the last couple of winners stay — a pattern library of what worked (winners-only by design, so it's study material, not a scoreboard).
5. Reference levels & tables. Stepped lines mark the previous day's and previous hour's high/low (the walls and fences other traders watch). A dashboard shows session, HTF bias, and zone counts; a pre-entry runsheet grades the nearest armed setup live against every rule (session, touches, gap, room, confluence, confirmation) and gives a GO / NO-TRADE verdict.
How it thinks — the engine
Under the hood it runs a per-zone state machine: each level independently moves live → broken → retested/failed/expired, so many setups can be tracked at once without interfering. Three principles govern everything: a break requires a body close through the zone (wick pokes are ignored); a retest needs a gap of at least one candle so the breakout candle can't be its own retest; and — critically — all decisions are made only at candle close, so signals, stops, and targets never drift intrabar or repaint.
Layered on top is a confluence grader (A/B/C) scoring each setup on higher-timeframe level overlap, breakout volume, and a quiet pullback — with an optional filter to trade only A or B+ setups. Session filters restrict signals to the high-volume London and New York windows (Asia is for marking levels, not trading them).
What it's for
Three jobs, in order of how you'd use them: it draws the map (which levels matter, which will hold vs break, for zone-to-zone planning), it triggers the trade (arms on break, fires on confirmed retest, with risk pre-set), and it keeps you honest (the audit shows real outcomes; the backtest sibling reports win rate and average R per grade so you tune on evidence, not vibes).
The one thing it deliberately doesn't do is pretend the strategy is a money printer — the audit only shows winners by design, and your first raw backtest came back at 25% win rate, which is exactly why the tuned strategy version and its per-grade stats exist: to find where the real edge lives before you risk anything. אינדיקטור

אינדיקטור

Ichimoku Cloud Thickness SpectrumOverview
Ichimoku Cloud Thickness Spectrum is an overlay for studying the geometry and relative thickness of the projected Ichimoku cloud. It plots the classical Tenkan-sen, Kijun-sen, Senkou Span A, Senkou Span B, and an optional Chikou Span, then adds a configurable research layer derived only from the distance and relationship between the two Senkou spans.
The script is designed to make three questions easier to inspect:
- How wide is the projected cloud in a unit suited to the current instrument?
- How unusual is that width compared with the cloud's own recent history?
- Is the smoothed cloud thickness expanding, contracting, or comparatively stable?
This is a context and visualization tool. It does not generate buy or sell instructions, forecasts, targets, stops, position sizing, or performance claims.
Original contribution
Cloud thickness is a known Ichimoku concept. The original contribution of this implementation is the integrated workflow used to transform raw Span A/B distance into a configurable research display:
1. Selectable ATR, percentage, or raw-price normalization.
2. Rolling empirical percentile ranking of the selected thickness measure.
3. Percentile-weighted cloud opacity and an optional dense inner core.
4. A stabilized expansion/contraction spine with a near-zero denominator floor and release-ratio hysteresis.
5. Confirmed thin-cloud seams filtered by thin-state membership, two-sided prominence, and minimum spacing.
6. Directional projected-cloud twist markers.
7. Separate handling of the newly calculated forward cloud and the historically shifted cloud aligned with the current price bar.
8. A bilingual confirmed/live readout, confirmed-bar alerts, and Data Window diagnostics.
The classical Ichimoku formulas are standard, widely known calculations. The percentile, motion-state, seam-filtering, visualization, readout, and alert logic were implemented for this script. No source code from another Community Script is reused.
Core calculations
- Tenkan-sen: midpoint of the highest high and lowest low over the Conversion length.
- Kijun-sen: midpoint of the highest high and lowest low over the Base length.
- Senkou Span A: average of Tenkan-sen and Kijun-sen.
- Senkou Span B: midpoint of the highest high and lowest low over the Span B length.
- Raw cloud thickness: absolute distance between Senkou Span A and Senkou Span B.
- Cloud midpoint: average of Senkou Span A and Senkou Span B.
Thickness modes and percentile ranking
- ATR: raw cloud thickness divided by ATR. This is the default and relates cloud width to recent price range.
- Percent: raw cloud thickness divided by the absolute close, multiplied by 100.
- Raw: the unnormalized price distance between Span A and Span B.
The selected measure is ranked against its own rolling history with a percent-rank calculation. A reading near 10 is relatively thin within the selected lookback, while a reading near 90 is relatively thick. The result is specific to the symbol, timeframe, settings, and available history; it is not a universal market-strength score.
Stabilized expansion and contraction
The selected thickness measure is smoothed with an EMA. A one-bar percentage change is then calculated. Near a cloud twist, Span A and Span B can converge and the previous thickness can approach zero, which can make an unrestricted percentage change unstable. To reduce this effect, the denominator cannot fall below a configurable fraction of a slower EMA baseline.
The state classifier also uses release-ratio hysteresis. Entry into expansion or contraction requires the main sensitivity threshold, while release from an existing state uses a smaller configurable threshold. This reduces bar-to-bar color chatter. The state uses the previous bar and does not rely on intrabar-only persistent memory.
Visual interpretation
- Teal cloud: Senkou Span A is at or above Senkou Span B.
- Red cloud: Senkou Span A is below Senkou Span B.
- More transparent cloud: lower thickness percentile.
- More visible cloud: higher thickness percentile.
- Dense inner core: optional emphasis when thickness percentile is above the selected threshold.
- Blue midpoint spine: thickness is in an expanding state.
- Purple midpoint spine: thickness is in a contracting state.
- Gray midpoint spine: thickness motion is inside the release threshold.
- Yellow upward/downward triangle: confirmed bullish/bearish projected-cloud twist.
- Small pink X: confirmed local thin-cloud seam that passed the thin-state, prominence, and spacing filters.
The cloud opacity and inner core encode relative thickness only. They do not guarantee support, resistance, continuation, reversal, or breakout behavior.
Filtered thin-cloud seams
A thin seam is not every low-thickness bar. It must be a confirmed local minimum in the thickness percentile, remain at or below the user-defined thin threshold, rebound by at least the selected prominence on both sides, and pass the minimum-spacing filter.
The pivot becomes known only after the selected number of right-side bars has closed. By default, a marker is not placed to the left of the bar where confirmation became available. The optional Allow seam placement before confirmation setting can place the marker at the original pivot-projected cloud position after confirmation. This changes the visual location only and does not make the event available earlier.
Projected cloud versus current aligned cloud
The newly calculated Span A and Span B values are displayed forward by the selected displacement. This positive offset shifts calculations made from current and historical bars into future chart positions; it does not access future market data.
Price-context calculations use a different alignment. They reference the historically shifted spans that are actually visible at the current price bar. Optional inside-cloud highlighting and current-cloud transition alerts therefore do not compare current price with the newly calculated cloud plotted in the future.
Forward readout, alerts, and research outputs
The three-line readout displays the thickness state and percentile, the selected normalized thickness value and motion state, and the future-cloud direction with Live or Confirmed status. English is the default. Japanese changes the readout, hover tooltip, and combined dynamic alert messages; input names and tooltips are bilingual.
Use confirmed values in readout is enabled by default. While the latest realtime bar is open, the label uses the previous closed bar. Once the latest bar is confirmed, it uses that bar. Users can disable the setting to inspect the open realtime bar, in which case the label shows Live and may change until close.
Confirmed-bar alert conditions are available for projected twists, thin/thick state transitions, current-cloud position transitions, expansion/contraction changes, and filtered thin seams. A combined bilingual alert is also available through Any alert() function call. Additional raw, normalized, percentile, motion, seam, current-cloud, direction, and state values are provided in the Data Window.
Realtime behavior and limitations
The script does not use request.security(), lookahead, or future bars. On an open realtime bar, Tenkan-sen, Kijun-sen, the projected spans, cloud opacity, and motion state can update as the bar's high, low, and close change. Confirmed historical values do not use intrabar-only memory. The supplied alert conditions are evaluated on confirmed bars, and the combined alert() call uses once-per-bar-close frequency.
Percentile readings require sufficient history and can show a warming-up state. Results depend on the symbol, timeframe, Ichimoku lengths, normalization basis, percentile lookback, and available data. Non-time-based charts and sparse datasets may behave differently from standard time-based candles.
A thick cloud is not automatically strong support or resistance. A thin or contracting cloud is not a breakout prediction. This script provides research context and should be combined with the user's own analysis and risk process.
日本語概要
Ichimoku Cloud Thickness Spectrumは、一目均衡表の将来雲について、方向だけでなく、厚み、履歴内の相対順位、拡大・収縮状態を研究するためのオーバーレイ型インジケーターです。転換線、基準線、先行スパン1・2、任意の遅行スパンを表示し、追加分析はすべて先行スパン1と2の距離および関係から算出します。
主な特徴
- 雲の厚みをATR比率、価格比率、価格差から選択可能。
- 選択した厚みを直近履歴内のパーセンタイルへ変換。
- 厚み順位を雲の透明度と任意の高密度インナーコアへ反映。
- ゼロ近傍の分母下限とヒステリシスを備えた拡大・収縮中心線。
- 薄い状態、左右プロミネンス、最小間隔を満たした確認済み局所薄化点。
- 上向き・下向きを分けた確認済み将来雲ツイスト。
- 将来へ描画する新規計算雲と、現在価格バーへ整列した過去計算雲を分離。
- 英語・日本語を切り替えられる将来ラベル、確定足アラート、データウィンドウ研究値。
雲の厚みという概念自体は既知です。本実装の差異は、生の雲幅を正規化し、履歴順位化し、厚みの動きを安定化し、薄化点を確認・選別し、それらを一貫した視覚表現と研究出力へ統合している点です。標準一目均衡表の計算式は広く知られた古典計算であり、追加した順位化、状態判定、薄化点フィルター、表示、ラベル、アラートのロジックは本スクリプト用に実装しています。他のCommunity Scriptのソースコードは再利用していません。
表示の読み方
- 青緑の雲: 先行スパン1が先行スパン2以上。
- 赤の雲: 先行スパン1が先行スパン2未満。
- 透明度が高い雲: 厚み順位が低い。
- 濃い雲とインナーコア: 厚み順位が高い。
- 青の中心線: 厚みが拡大状態。
- 紫の中心線: 厚みが収縮状態。
- 灰色の中心線: 安定状態。
- 黄色の三角: 確認済みの上向き・下向き将来雲ツイスト。
- 小さなピンクのX: 条件を満たした確認済み局所薄化点。
厚み順位は銘柄、時間足、設定、参照期間、利用可能な履歴に依存する相対値です。雲の濃さやインナーコアは支持抵抗の保証ではありません。
確認、シフト、ライブ動作
将来雲は、現在および過去バーから計算した先行スパンを正のoffsetで将来位置へ描画したもので、未来データを取得していません。現在価格との関係には、現在バー上に実際に整列している過去計算の先行スパンを使用します。
薄化点は右側に指定本数の確定バーを必要とするため、認識に意図的な遅延があります。初期設定では確認可能になったバーより左側へ表示しません。任意設定で元の投影位置へ表示する場合も、認識自体は確認後です。
未確定リアルタイムバーでは、高値・安値・終値の更新に伴い、転換線、基準線、先行スパン、雲の透明度、拡大・収縮状態が終値確定まで変化する場合があります。将来ラベルは初期設定で確定値を使用し、用意したアラートは確定足で判定します。
本インジケーターは研究・可視化ツールです。売買指示、将来予測、目標価格、損切り、ポジションサイズ、成績統計、投資助言を提供しません。厚い雲を必ず強い支持抵抗、薄い雲や収縮中の雲を必ずブレイクする状態とは定義していません。 אינדיקטור

אינדיקטור

אינדיקטור

ABE'S KNN Machine Learning Momentum Indicator//@version=5
indicator("ABE'S KNN Machine Learning Momentum Indicator", overlay=true, max_bars_back=2000)
// ==========================================
// --- CONSTANTS & STYLING ---
// ==========================================
color_bull = color.new(#00ffbb, 0)
color_bear = color.new(#ff3355, 0)
color_bull_dim = color.new(#00ffbb, 50)
color_bear_dim = color.new(#ff3355, 50)
color_neutral = color.new(#64748b, 20)
color_gold = color.new(#ffd700, 0)
// ==========================================
// --- MA SELECTOR & HELPER FUNCTIONS ---
// ==========================================
f_zlsma(s, l) =>
lsma = ta.linreg(s, l, 0)
lsma + (lsma - ta.sma(s, l))
f_dema(s, l) =>
e1 = ta.ema(s, l)
2 * e1 - ta.ema(e1, l)
f_tema(s, l) =>
e1 = ta.ema(s, l)
e2 = ta.ema(e1, l)
3 * (e1 - e2) + ta.ema(e2, l)
f_thma(s, l) =>
l_3 = math.max(1, math.round(l / 3))
l_2 = math.max(1, math.round(l / 2))
ta.wma(ta.wma(s, l_3) * 3 - ta.wma(s, l_2) - ta.wma(s, l), l)
calcMA(type, s, l) =>
len = math.max(1, l)
switch type
"SMA" => ta.sma(s, len)
"EMA" => ta.ema(s, len)
"DEMA" => f_dema(s, len)
"TEMA" => f_tema(s, len)
"LSMA" => ta.linreg(s, len, 0)
"WMA" => ta.wma(s, len)
"HMA" => ta.hma(s, len)
"ZLSMA" => f_zlsma(s, len)
"SMMA" => ta.rma(s, len)
"THMA" => f_thma(s, len)
=> ta.sma(s, len)
// ==========================================
// --- INPUT PARAMETERS ---
// ==========================================
group_ml = "🧠 Machine Learning Engine"
k_neighbors = input.int(100, "K-Neighbors (K)", minval=1, group=group_ml, tooltip="Number of nearest neighbors to consider.")
window_size = input.int(1200, "Learning Window Size", minval=10, group=group_ml, tooltip="Historical data lookback for training.")
prob_threshold = input.float(0.9, "Prediction Threshold", minval=0.1, maxval=1.0, step=0.01, group=group_ml, tooltip="Confidence level required for a signal.")
momentum_window = input.int(4, "Momentum Window", minval=1, group=group_ml, tooltip="Look-back period for labeling price direction.")
group_feat = "📊 Feature Engineering"
feat_ma_type = input.string("SMA", "Feature MA Type", options= , group=group_feat, tooltip="MA type used for feature calculation.")
rsi_short_len = input.int(2, "Short RSI Period", group=group_feat)
rsi_mid_len = input.int(3, "Mid RSI Period", group=group_feat)
rsi_long_len = input.int(4, "Long RSI Period", group=group_feat)
ma_short_len = input.int(2, "Short MA Period", group=group_feat)
ma_medium_len = input.int(3, "Medium MA Period", group=group_feat)
ma_long_len = input.int(4, "Long MA Period", group=group_feat)
signal_len = input.int(4, "Signal Line Period", group=group_feat)
p_param = input.float(4.0, "Minkowski Parameter (p)", group=group_feat, tooltip="Distance metric exponent. 2=Euclidean, 1=Manhattan.")
w_param = input.float(4.0, "Shape Parameter", group=group_feat, tooltip="Gausian Weighting exponent.")
group_filter = "🛡️ Signal Filters"
filter_mode = input.string("Price & Fast MA", "Filter Condition Mode", options= , group=group_filter, tooltip="Defines which trend conditions must be met for a 'Major' signal.")
filter_ma_type = input.string("EMA", "Filter MA Type", options= , group=group_filter)
fast_filter_len = input.int(20, "Fast Filter Period", minval=1, group=group_filter)
slow_filter_len = input.int(50, "Slow Filter Period", minval=1, group=group_filter)
group_pca = "⚡ Dimensionality Reduction"
use_pca = input.bool(true, "Enable PCA Compression", group=group_pca, tooltip="Compresses features into 3 Principal Components to reduce noise.")
group_vis = "🎨 Visual Analytics"
use_bar_color = input.bool(true, "Dynamic Bar Coloring", group=group_vis, tooltip="Colors bars based on KNN prediction confidence.")
show_vwap = input.bool(true, "Show VWAP", group=group_vis)
group_mom = "🚀 Momentum Entry Engine"
use_momentum_filter = input.bool(true, "Require Momentum Confirmation", group=group_mom)
use_htf_filter = input.bool(true, "Require 15m Trend Alignment", group=group_mom)
use_vwap_filter = input.bool(true, "Require VWAP Alignment", group=group_mom)
use_adx_filter = input.bool(true, "Require ADX Strength", group=group_mom)
adx_len = input.int(14, "ADX Length", minval=3, group=group_mom)
adx_min = input.float(18.0, "Minimum ADX", minval=5, maxval=60, step=1, group=group_mom)
atr_len = input.int(14, "ATR Length", minval=1, group=group_mom)
vol_len = input.int(30, "Volume Average", minval=5, group=group_mom)
relative_vol_min = input.float(1.20, "Relative Volume Minimum", minval=0.5, step=0.05, group=group_mom)
body_atr_min = input.float(0.35, "Minimum Body ATR", minval=0.05, step=0.05, group=group_mom)
range_atr_min = input.float(0.60, "Minimum Range ATR", minval=0.10, step=0.05, group=group_mom)
close_strength_min = input.float(65.0, "Minimum Close Strength %", minval=50, maxval=95, step=5, group=group_mom)
breakout_lookback = input.int(12, "Breakout Lookback", minval=3, maxval=100, group=group_mom)
pullback_tolerance_atr = input.float(0.20, "Pullback Tolerance ATR", minval=0.02, step=0.01, group=group_mom)
entry_mode = input.string("Either", "Entry Type", options= , group=group_mom)
signal_cooldown = input.int(10, "Signal Cooldown Bars", minval=0, maxval=100, group=group_mom)
show_setup_markers = input.bool(true, "Show Setup Markers", group=group_mom)
// ==========================================
// --- LABELING (Supervised Learning) ---
// ==========================================
target = 1
for i = 0 to momentum_window - 1
if close >= close
target := 0
target := target == 0 ? -1 : target
if target == -1
for i = 0 to momentum_window - 1
if close <= close
target := 0
// ==========================================
// --- FEATURE CALCULATION & NORMALIZATION ---
// ==========================================
normalize(src, len) =>
float _mean = ta.sma(src , len)
float _std = ta.stdev(src , len)
(src - _mean) / math.max(_std, 0.00001)
f_rsi_s = ta.rsi(close, rsi_short_len)
f_rsi_m = ta.rsi(close, rsi_mid_len)
f_rsi_l = ta.rsi(close, rsi_long_len)
f_ma_s_dev = (close - calcMA(feat_ma_type, close , ma_short_len)) / calcMA(feat_ma_type, close , ma_short_len) * 100
f_ma_m_dev = (close - calcMA(feat_ma_type, close , ma_medium_len)) / calcMA(feat_ma_type, close , ma_medium_len) * 100
f_ma_l_dev = (close - calcMA(feat_ma_type, close , ma_long_len)) / calcMA(feat_ma_type, close , ma_long_len) * 100
f_rsi_s_sig_dist = f_rsi_s - ta.sma(f_rsi_s , signal_len)
f_rsi_m_sig_dist = f_rsi_m - ta.sma(f_rsi_m , signal_len)
f_rsi_l_sig_dist = f_rsi_l - ta.sma(f_rsi_l , signal_len)
f_rsi_s_z = normalize(f_rsi_s, window_size)
f_rsi_m_z = normalize(f_rsi_m, window_size)
f_rsi_l_z = normalize(f_rsi_l, window_size)
f_ma_s_dev_z = normalize(f_ma_s_dev, window_size)
f_ma_m_dev_z = normalize(f_ma_m_dev, window_size)
f_ma_l_dev_z = normalize(f_ma_l_dev, window_size)
f_rsi_s_sd_z = normalize(f_rsi_s_sig_dist, window_size)
f_rsi_m_sd_z = normalize(f_rsi_m_sig_dist, window_size)
f_rsi_l_sd_z = normalize(f_rsi_l_sig_dist, window_size)
body_size = normalize(close - open, window_size)
body_ratio = normalize((close - open)/(high-low), window_size)
// ==========================================
// --- DIMENSIONALITY REDUCTION ---
// ==========================================
float pc1 = 0.0, float pc2 = 0.0, float pc3 = 0.0, float pc4 = 0.0
if use_pca
pc1 := (f_rsi_s_z + f_rsi_m_z + f_rsi_l_z)
pc2 := (f_ma_s_dev_z + f_ma_m_dev_z + f_ma_l_dev_z) * 2.0
pc3 := (f_rsi_s_sd_z + f_rsi_m_sd_z + f_rsi_l_sd_z) * 0.5
pc4 := (body_size + body_ratio) * 0.5
else
pc1 := f_rsi_m_z
pc2 := f_ma_m_dev_z
pc3 := f_rsi_m_sd_z
pc4 := (body_size)
// ==========================================
// --- KNN CORE ENGINE ---
// ==========================================
float prob_up = 0.0, float prob_down = 0.0
var float distances = array.new_float(0)
var float labels = array.new_float(0)
stride = momentum_window
if bar_index > window_size + momentum_window
array.clear(distances)
array.clear(labels)
for i = momentum_window to window_size + momentum_window by stride
float d1 = math.abs(pc1 - pc1 )
float d2 = math.abs(pc2 - pc2 )
float d3 = math.abs(pc3 - pc3 )
float d4 = math.abs(pc4 - pc4 )
float dist_knn = math.pow(math.pow(d1, p_param) + math.pow(d2, p_param) + math.pow(d3, p_param) + math.pow(d4, p_param), 1/p_param)
array.push(distances, dist_knn)
array.push(labels, target )
if array.size(distances) >= k_neighbors
int sorted_indices = array.sort_indices(distances, order.ascending)
float sum_weight_up = 0.0, float sum_weight_down = 0.0, float total_weight = 0.0
float dist_sorted = array.copy(distances)
array.sort(dist_sorted)
float sigma = array.get(dist_sorted, math.min(int(k_neighbors/2), array.size(dist_sorted)-1))
sigma := math.max(sigma, 0.0001)
for j = 0 to k_neighbors - 1
int idx = array.get(sorted_indices, j)
float d = array.get(distances, idx)
float lbl = array.get(labels, idx)
float weight = math.exp(-math.pow(d, w_param) / (2 * math.pow(sigma, 2)))
if lbl == 1
sum_weight_up += weight
else if lbl == -1
sum_weight_down += weight
total_weight += weight
prob_up := total_weight > 0 ? sum_weight_up / total_weight : 0.0
prob_down := total_weight > 0 ? sum_weight_down / total_weight : 0.0
// ==========================================
// --- FILTER CALCULATION ---
// ==========================================
fast_ma = calcMA(filter_ma_type, close, fast_filter_len)
slow_ma = calcMA(filter_ma_type, close, slow_filter_len)
bool filter_bull = true
bool filter_bear = true
switch filter_mode
"Price & Fast MA" =>
filter_bull := close > fast_ma
filter_bear := close < fast_ma
"Fast MA & Slow MA" =>
filter_bull := fast_ma > slow_ma
filter_bear := fast_ma < slow_ma
"Price & Fast & Slow" =>
filter_bull := close > fast_ma and fast_ma > slow_ma
filter_bear := close < fast_ma and fast_ma < slow_ma
=> // "None"
filter_bull := true
filter_bear := true
// ==========================================
// --- MOMENTUM CONFIRMATION ENGINE ---
// ==========================================
atr_m = ta.atr(atr_len)
avg_vol_m = ta.sma(volume, vol_len)
relative_volume = avg_vol_m > 0 ? volume / avg_vol_m : 0.0
bar_range_m = math.max(high - low, syminfo.mintick)
body_m = math.abs(close - open)
bull_close_strength = (close - low) / bar_range_m * 100.0
bear_close_strength = (high - close) / bar_range_m * 100.0
= ta.dmi(adx_len, adx_len)
htf_fast = request.security(syminfo.tickerid, "15", ta.ema(close, 9), barmerge.gaps_off, barmerge.lookahead_off)
htf_slow = request.security(syminfo.tickerid, "15", ta.ema(close, 21), barmerge.gaps_off, barmerge.lookahead_off)
session_vwap = ta.vwap(hlc3)
volume_ok = relative_volume >= relative_vol_min
adx_ok = not use_adx_filter or adx_value >= adx_min
htf_bull_ok = not use_htf_filter or htf_fast > htf_slow
htf_bear_ok = not use_htf_filter or htf_fast < htf_slow
vwap_bull_ok = not use_vwap_filter or close > session_vwap
vwap_bear_ok = not use_vwap_filter or close < session_vwap
bull_expansion = close > open and body_m >= atr_m * body_atr_min and bar_range_m >= atr_m * range_atr_min and bull_close_strength >= close_strength_min
bear_expansion = close < open and body_m >= atr_m * body_atr_min and bar_range_m >= atr_m * range_atr_min and bear_close_strength >= close_strength_min
prior_high = ta.highest(high, breakout_lookback)
prior_low = ta.lowest(low, breakout_lookback)
bull_breakout = close > prior_high and close <= prior_high
bear_breakout = close < prior_low and close >= prior_low
bull_pullback = low <= fast_ma + atr_m * pullback_tolerance_atr and close > fast_ma and close > open
bear_pullback = high >= fast_ma - atr_m * pullback_tolerance_atr and close < fast_ma and close < open
long_location_ok = entry_mode == "Pullback" ? bull_pullback : entry_mode == "Breakout" ? bull_breakout : bull_pullback or bull_breakout
short_location_ok = entry_mode == "Pullback" ? bear_pullback : entry_mode == "Breakout" ? bear_breakout : bear_pullback or bear_breakout
long_momentum_ok = not use_momentum_filter or (filter_bull and htf_bull_ok and vwap_bull_ok and adx_ok and volume_ok and bull_expansion and long_location_ok)
short_momentum_ok = not use_momentum_filter or (filter_bear and htf_bear_ok and vwap_bear_ok and adx_ok and volume_ok and bear_expansion and short_location_ok)
// ==========================================
// --- SIGNAL GENERATION ---
// ==========================================
bool raw_long_signal = ta.crossover(prob_up, prob_threshold)
bool raw_short_signal = ta.crossover(prob_down, prob_threshold)
var int last_long_bar = na
var int last_short_bar = na
long_setup = prob_up >= prob_threshold and filter_bull and htf_bull_ok and vwap_bull_ok and adx_ok and long_location_ok
short_setup = prob_down >= prob_threshold and filter_bear and htf_bear_ok and vwap_bear_ok and adx_ok and short_location_ok
long_signal = barstate.isconfirmed and raw_long_signal and long_momentum_ok and (na(last_long_bar) or bar_index - last_long_bar > signal_cooldown)
short_signal = barstate.isconfirmed and raw_short_signal and short_momentum_ok and (na(last_short_bar) or bar_index - last_short_bar > signal_cooldown)
if long_signal
last_long_bar := bar_index
if short_signal
last_short_bar := bar_index
setup_long_marker = show_setup_markers and long_setup and not long_setup
setup_short_marker = show_setup_markers and short_setup and not short_setup
// ==========================================
// --- VISUALIZATION & PLOTTING ---
// ==========================================
color g_color = prob_up > prob_down ? color.from_gradient(prob_up, 0.4, 1.0, color_neutral, color_bull) : color.from_gradient(prob_down, 0.4, 1.0, color_neutral, color_bear)
barcolor(use_bar_color ? g_color : na)
bgcolor(long_signal ? color.new(color_bull, 90) : short_signal ? color.new(color_bear, 90) : na)
plot_fast = (filter_mode == "Price & Fast MA" or filter_mode == "Fast MA & Slow MA" or filter_mode == "Price & Fast & Slow")
plot_slow = (filter_mode == "Fast MA & Slow MA" or filter_mode == "Price & Fast & Slow")
plot(plot_fast ? fast_ma : na, "Fast Filter MA", color=color.blue, linewidth=1)
plot(plot_slow ? slow_ma : na, "Slow Filter MA", color=color.orange, linewidth=1)
plotshape(setup_long_marker, "Long Setup", shape.circle, location.belowbar, color_bull_dim, size=size.tiny, text="SET", textcolor=color.white)
plotshape(setup_short_marker, "Short Setup", shape.circle, location.abovebar, color_bear_dim, size=size.tiny, text="SET", textcolor=color.white)
plotshape(long_signal, "Momentum BUY", shape.labelup, location.belowbar, color_bull, size=size.large, text="BUY", textcolor=color.black)
plotshape(short_signal, "Momentum SELL", shape.labeldown, location.abovebar, color_bear, size=size.large, text="SELL", textcolor=color.white)
if long_signal
label.new(bar_index, low, "BUY " + str.tostring(prob_up * 100.0, "#") + "%", style=label.style_label_up, color=color_bull, textcolor=color.black, size=size.large)
if short_signal
label.new(bar_index, high, "SELL " + str.tostring(prob_down * 100.0, "#") + "%", style=label.style_label_down, color=color_bear, textcolor=color.white, size=size.large)
plot(show_vwap ? session_vwap : na, "Session VWAP", color=color_gold, linewidth=2)
// ==========================================
// --- ALERTS ---
// ==========================================
alert_long = long_signal and filter_bull
alert_short = short_signal and filter_bear
alert_combo = alert_long or alert_short
alertcondition(alert_long, "KNN Major Long", "Bullish Signal with Filter Confirmation")
alertcondition(alert_short, "KNN Major Short", "Bearish Signal with Filter Confirmation")
alertcondition(alert_combo, "KNN Combo Alert", "Major KNN Signal (Bull or Bear) with Filter Confirmation") אינדיקטור

Auto Trend Channel & Breakout Expectancy in ROVERVIEW
An auto-drawn trend channel is easy. Knowing whether breaking it has ever paid on YOUR symbol is not — and it is the only thing that matters.
This tool draws the channel objectively and then does the part nobody else does: it forward-resolves every historical break through a real target and stop, and reports, in R, what breaks like the current one have actually returned. Not a prediction. A track record.
Expectancy exp +1.24R · need 15% @ RR 6.0
HV win/loss 38/59% n400 ✓
MV win/loss 32/65% n150 ✓
LV win/loss 17/83% n55
Null / net net 1.29R t=3.1 ✓
It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.
HOW THE CHANNEL IS BUILT — objectively, no hand-placed anchors
The support and resistance lines come from a CONVEX HULL over confirmed pivots, not from two points a human chose. The opposite boundary is drawn parallel, and the channel WIDTH becomes the measured-move target. Because the construction is mechanical, the same rule produces the same channel on every symbol and every timeframe — there is nothing to curve-fit.
HOW A BREAK IS GRADED — and why volume is split three ways
A break is a confirmed CLOSE beyond the boundary. Every break is then sorted by its break-bar volume percentile into HV / MV / LV (high / medium / low), and each tier is calibrated SEPARATELY.
That split is the point. "Breakouts need volume" is repeated everywhere and tested almost nowhere. Here you can read straight off the panel whether heavy breaks on your instrument actually pay more than thin ones — and often they do not, which is worth knowing before you wait for a volume confirmation that costs you the entry.
THE FORWARD TEST — expectancy in R, on identical geometry
Every break is resolved through a triple barrier: a target at the channel-width move, a stop at a fixed ATR distance, and a horizon. Win, loss, or chop. The expectancy is the exact realized R per trade — a win contributes +RR, a loss contributes −1, chop contributes 0 — so the win rate and the R:R are on the SAME footing, computed from the same resolved trades. There is no mixing of a win rate from one calculation with an R:R from another.
The R:R shown is the target-to-stop RATIO, and it is deliberately not the headline. A 6:1 target sounds wonderful and is reached maybe a third of the time; quoting it alone flatters a low-hit-rate system. So the panel leads with the realized EXPECTANCY, then states the breakeven win rate the geometry requires, then shows the win rate actually achieved. Expectancy first, because expectancy is the thing that is actually true.
Nothing is rated until a tier has at least 30 resolved trades. Below that, no checkmark, no verdict, no meta call — a Wilson floor on a dozen trials is too wide to certify anything, and pretending otherwise is how bad tiers get a green tick.
THE RANDOM-DIRECTION NULL — the honesty check
Here is the trap this defends against. A 6:1 target with a nearby stop is an asymmetric payoff, and on a drifting instrument an asymmetric payoff makes money in a RANDOM direction — the geometry earns, not the signal. So for every real break the script ALSO runs a coin-flip-direction trade with the identical target and stop, and reports its expectancy alongside.
If the null earns as much as the signal, the "edge" is just the geometry capturing drift, and you should believe the null. And it is now TESTED, not just displayed: a Welch t between the signal's realized-R distribution and the null's turns "net 1.29R" into "net 1.29R, t = 3.1, real" — or into "ns", not significant, which is the more common and more honest outcome.
THE OPTIONAL META-LABEL — a learned second opinion
An online logistic model trains on this script's own resolved outcomes and outputs a calibrated probability of follow-through for the current break. No hand-tuned weights; it self-corrects as more breaks resolve, and it reports its own reliability (the realized win rate inside each probability bin) so you can see whether its confidence is earned. It is off by default and it never overrides the forward test — it is a second opinion, not the verdict.
THE ANTI-BIAS GUARDS
ENTRY IS THE CLOSE (or, in retest mode, the line touch) — a break is a signal, not a fill, and entering at a better price than the trade actually offered would manufacture an edge.
Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are scored as chop (zero), not as wins.
THE NULL is direction-randomised on the same geometry, which is what isolates signal from payoff structure. Every rating is gated by a minimum sample and a Wilson lower bound, and the null gap is significance-tested. Nothing here is asserted that has not cleared a test.
NON-REPAINT
Confirmed pivots, confirmed-close breaks, and forward-resolved calibration that never looks ahead. The channel can extend and re-fit as new pivots confirm, but a resolved trade is never re-scored, and no barrier is evaluated on a bar that has not closed.
DATA AND SCOPE
Any symbol, any timeframe. ATR-normalised throughout. Volume is used for the tier split; without it the tiers collapse to one and everything else still works.
EXPORTS (Data Window — consume from other scripts via input.source())
Channel high, channel low, break direction, volume tier, entry, stop, target, per-tier expectancy, null expectancy, meta probability — see the Exports group.
CONCEPT CREDIT
The convex-hull approach to objective trendlines, the triple-barrier forward-labelling method and the meta-labelling idea are from Marcos Lopez de Prado ("Advances in Financial Machine Learning"). The trading-range break as a formal, testable rule was first studied at scale by Brock, Lakonishok and LeBaron (Journal of Finance, 1992); its vulnerability to data-snooping was shown by Sullivan, Timmermann and White (1999) — which is exactly why this tool measures the rule on your instrument instead of asserting it. Wilson score interval — E. B. Wilson (1927). Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.
The convex-hull channel implementation, the volume-tier calibration, the random-direction null with its significance test, and the online meta-label are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.
HONESTY AND LIMITATIONS
Calibration is IN-SAMPLE, fixed-barrier, and assumes idealised fills — no commission, no slippage, no partial fills. It describes the past; it does not predict the future. Real costs will reduce every number, and they reduce the low-hit-rate high-RR tiers most.
Overlapping windows mean the samples are not fully independent, so treat the t-stats as directional evidence, not exact p-values. A tier that is proven in-sample is not guaranteed out-of-sample.
The null being beaten is the single most important line on the panel, and on many instruments it will read "ns". That is a real result. A tool that cannot report "no edge here" is selling you something.
Nothing in this script predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. אינדיקטור

Median Cascade Trend [BackQuant]Median Cascade Trend
Overview
Median Cascade Trend is a noise-resistant trend-following indicator that combines multiple causal median filters , an Ehlers-style two-pole Super Smoother , and a configurable chop-gating system .
Its purpose is to identify meaningful directional structure while rejecting the types of price movement that frequently cause conventional moving averages to whipsaw:
Single-bar spikes
Short-lived price shocks
Irregular wicks
Low-efficiency sideways movement
Weak slopes that do not represent genuine directional progress
The indicator processes price in three distinct stages:
A median-filter cascade removes impulsive and short-duration noise.
A two-pole low-pass filter smooths the remaining structural signal.
A chop gate decides whether a change in direction is strong enough to update the active trend state.
This creates a trend line that is intentionally more selective than a standard moving average. The line itself can continue evolving, but trend-state changes are only accepted when the underlying movement passes the chosen quality tests.
The result is a system that separates:
The estimated trend line
The raw direction of that line
The confirmed trend regime
That distinction is important. The indicator does not assume that every small turn in a smoothed line represents a valid trend reversal.
Core idea
Most trend filters are built around linear averaging. They combine historical prices using fixed or exponentially decaying weights.
Examples include:
SMA
EMA
WMA
HMA
DEMA
These filters are effective for general smoothing, but they have a weakness: a single extreme observation can influence the output immediately.
If one bar produces a large wick or temporary price shock, a moving average will usually be pulled toward that value because it includes the magnitude of every observation.
A median filter behaves differently.
Instead of averaging the values inside a window, it sorts them and selects the middle observation. This makes it highly resistant to isolated extremes.
Median Cascade Trend uses this property repeatedly before applying traditional low-pass smoothing.
The central idea is:
Remove impulsive noise first.
Smooth the cleaned signal second.
Confirm direction only when the movement is efficient or sufficiently steep.
This ordering is deliberate. Smoothing a noisy series and filtering noise before smoothing are not the same thing.
Where median filtering comes from
Median filters are widely used in digital signal processing, image processing, and engineering.
One of their best-known applications is the removal of impulse noise , sometimes called salt-and-pepper noise in image processing.
Impulse noise consists of isolated extreme observations that are not representative of the surrounding signal.
In market data, comparable events include:
Temporary liquidity gaps
Single-bar stop runs
Erroneous prints
Sharp wick reversals
News spikes that immediately retrace
A linear smoother such as an SMA or EMA cannot distinguish between an important sustained move and an isolated outlier. Both are included according to their numerical magnitude.
A median filter is nonlinear. It selects the central-ranked value rather than calculating an arithmetic mean.
For example, consider five observations:
100
101
102
103
140
The average is:
109.2
The median is:
102
The isolated value at 140 significantly distorts the average but has almost no effect on the median.
This is why median filtering is especially useful when the objective is to preserve structural turns while rejecting isolated noise.
What makes a median filter nonlinear
A normal moving average can be represented as a weighted sum of its inputs.
A median filter cannot.
Its output depends on the ordering of observations, not their arithmetic combination. This makes it a nonlinear filter.
That has several important consequences:
Outliers have limited influence.
Edges and structural shifts can be preserved more cleanly.
The response is not equivalent to ordinary low-pass averaging.
The filter may hold a value until enough observations confirm a change.
In trading terms, the median filter often behaves more like a structural selector than a conventional average.
What “causal” means
The median stages in this indicator are causal.
A causal filter uses:
The current bar
Past bars
It does not use future observations.
This matters because many visually smooth filtering methods can only produce their best result by centering the calculation around the current point, which requires future data.
This script does not do that.
Every value is calculated from information available at that bar, making the filter suitable for live use.
Why use a cascade of median filters
A single median filter can remove isolated spikes, but noise does not always occur as one extreme bar.
It can appear as:
Two-bar shocks
Short bursts of alternating movement
Small clusters of irregular candles
Residual distortion left after the first filtering pass
A cascade applies multiple median stages sequentially:
Stage 1 processes the original source.
Stage 2 processes the output of Stage 1.
Stage 3 processes the output of Stage 2.
Each stage removes a different layer of short-duration instability.
The process is similar to progressively cleaning a signal:
The first stage removes obvious impulse noise.
The second stage removes remaining short-term irregularity.
The third stage produces a more stable structural series before low-pass smoothing.
Median Stage 1
The first median stage is intended to reject isolated one-bar disturbances.
With a short setting such as 3:
The filter remains responsive.
Single-bar spikes are strongly suppressed.
Most genuine multi-bar movement remains visible.
This is the most tactical stage.
Median Stage 2
The second stage receives an already-cleaned input.
Its role is to remove:
Short-duration residual noise
Small alternating movements
Irregularity that survived the first stage
A slightly longer setting such as 5 creates stronger structural consistency.
Median Stage 3
The third stage provides the final nonlinear cleaning pass.
With a longer setting such as 7:
The output becomes more stable.
Short-lived reversals are reduced.
Only more persistent changes are passed into the low-pass stage.
This is the most conservative median stage.
Cascade Stages input
The user can select how many median stages are active:
1 stage: fastest and most responsive
2 stages: balanced noise rejection
3 stages: strongest impulse-noise suppression
The unused stages are still calculated internally, but the selected stage determines which output is sent into the Super Smoother.
Why cascade instead of one very long median
Applying several shorter filters is not always equivalent to applying one very long median filter.
A long median window can:
Delay structural changes heavily
Flatten shorter trend legs
Become insensitive to local turns
A cascade allows the filtering process to be distributed across stages.
This provides greater control over:
How aggressively isolated noise is removed
How much short-duration movement survives
How smooth the final structural input becomes
It also lets users build a progression such as 3, 5, and 7 rather than applying one blunt window.
The low-pass stage
After the median cascade, the signal is passed into a two-pole Super Smoother .
The median cascade removes nonlinear impulse noise, but its output can still contain:
Small step changes
Residual high-frequency movement
Sharp transitions caused by median replacement
The Super Smoother converts that cleaned but potentially stepped series into a smoother trend line.
This creates a hybrid filtering system:
Nonlinear median filtering for outlier rejection
Recursive low-pass filtering for smooth trend extraction
These components solve different problems.
Where the Super Smoother comes from
The Super Smoother is associated with John F. Ehlers’ application of digital signal processing techniques to financial markets.
It is based on the behavior of a two-pole low-pass filter and is designed to suppress high-frequency components more effectively than many conventional moving averages.
Traditional moving averages are simple smoothers, but they are not necessarily optimized as frequency-selective filters.
The Super Smoother uses recursively calculated coefficients derived from:
Exponential decay
Trigonometric terms
A selected cutoff period
The objective is to reduce high-frequency market noise while retaining lower-frequency directional structure.
What a low-pass filter does
A low-pass filter allows slow-moving components of a signal to pass while reducing fast-moving components.
In market terms:
Slow components represent broader trend structure.
Fast components represent short-term noise, rapid oscillation, and microstructure disturbance.
The Low-Pass Length determines the separation.
Lower values:
Allow more short-term movement through.
React faster.
Produce more turns.
Higher values:
Reject more high-frequency movement.
Produce a smoother trend line.
Respond later to structural changes.
Why use a two-pole filter
The number of poles broadly describes the order and steepness of a filter.
A two-pole filter generally provides:
Stronger attenuation of high-frequency noise than a one-pole filter.
A smoother output.
A more defined frequency response.
It also uses prior filter outputs recursively, allowing substantial smoothing without requiring an extremely long direct averaging window.
The full signal-processing chain
The calculation can be understood as:
Raw price source
Median Stage 1
Optional Median Stage 2
Optional Median Stage 3
Two-pole Super Smoother
Direction measurement
Chop-quality validation
Persistent trend state
Each layer has a distinct purpose.
Median cascade
Rejects isolated and short-lived noise.
Super Smoother
Reduces the remaining high-frequency variation.
Direction logic
Determines whether the final line is rising or falling.
Chop gate
Determines whether that directional change is trustworthy enough to update the confirmed trend.
Trend direction calculation
The raw direction is determined by comparing the current trend line with its value several bars ago:
Bullish if trendLine > trendLine
Bearish if trendLine < trendLine
Neutral if equal
The Direction Lookback controls how much movement is required before the line is classified as rising or falling.
A one-bar comparison is extremely responsive but can detect tiny slope changes.
A longer comparison:
Measures movement across a wider interval.
Reduces sensitivity to one-bar flattening.
Produces more stable raw direction.
Raw trend versus confirmed trend
One of the most important design choices is that the script separates:
Raw trend
Confirmed trend
The raw trend reflects the current direction of the filtered line.
The confirmed trend is persistent and changes only when:
The raw trend points in a new direction.
The chop gate is open.
If the line turns but the gate is closed:
The active trend state remains unchanged.
The attempted flip can optionally be displayed as blocked.
This prevents every small line turn from immediately becoming a regime reversal.
Why a chop filter is needed
Even an advanced smoother can turn repeatedly during sideways markets.
Smoothing reduces noise, but it does not determine whether movement is:
Directional
Efficient
Large enough relative to volatility
A line can move upward and downward in a range while making almost no net progress.
The chop gate addresses this by evaluating two separate properties:
Directional efficiency
ATR-normalized slope
Efficiency Ratio
The first gate component measures how efficiently the trend line has moved over a selected window.
The calculation compares:
Net movement
Total movement
Net movement is:
|trendLine - trendLine |
Total movement is:
Sum of |bar-to-bar changes in trendLine|
The Efficiency Ratio is:
Efficiency = Net Movement / Total Movement
The result ranges approximately from 0 to 1.
Efficiency near 1
The line has moved mostly in one direction.
Example:
It advanced 10 units.
Its total path was approximately 11 units.
This indicates a clean directional move.
Efficiency near 0
The line has moved back and forth without achieving much net progress.
Example:
It travelled 20 units in total.
But ended only 1 unit from where it started.
This indicates chop.
Where the Efficiency Ratio comes from
The Efficiency Ratio is commonly associated with Perry Kaufman’s work on adaptive market analysis and the Kaufman Adaptive Moving Average.
Its purpose is to distinguish directional movement from noisy movement.
It does not measure the size of a move alone.
It measures the quality of the path.
This makes it highly suitable as a trend gate.
A market can be volatile but inefficient. It can move aggressively in both directions and still make little progress.
The Efficiency Ratio helps identify that distinction.
Minimum Efficiency
The Minimum Efficiency input determines the directional quality required for the efficiency condition to pass.
Lower values:
Allow more irregular movement.
Open the gate more frequently.
Produce earlier but noisier trend changes.
Higher values:
Require cleaner directional travel.
Block more sideways flips.
Produce fewer but more selective regime changes.
ATR-Normalized Slope
The second gate component measures how large the trend-line movement is relative to current market volatility.
It calculates:
|trendLine - trendLine | / ATR
This converts the line’s movement into ATR units.
Without normalization, a slope of 10 points could be:
Large for one instrument
Negligible for another
Large in a quiet regime
Small during extreme volatility
ATR normalization makes the slope more comparable across assets and regimes.
What normalized slope measures
The Efficiency Ratio asks:
Was the movement directionally clean?
ATR-normalized slope asks:
Was the movement large enough to matter?
These are different questions.
A move can be highly efficient but extremely small.
For example:
A perfectly smooth drift of only 0.02 ATR may not justify a new trend regime.
A move can also be large but inefficient:
A violent range may travel several ATRs while repeatedly reversing.
Using both filters gives a more complete view of trend quality.
Minimum ATR-Normalized Slope
The Minimum ATR-Normalized Slope defines the movement threshold.
Lower values:
Accept weaker slopes.
React sooner.
Allow more low-energy flips.
Higher values:
Require stronger displacement.
Reduce weak trend transitions.
Delay signals until movement becomes more meaningful.
Gate modes
The indicator provides four chop-gate modes.
Efficiency Ratio
Only directional efficiency is required.
Best suited for users who care primarily about whether movement is clean, regardless of its exact magnitude.
ATR-Normalized Slope
Only slope strength is required.
Best suited for users who want movement to exceed a volatility-adjusted threshold, even if the path is not perfectly efficient.
Both
Both conditions must pass:
Efficiency must be high enough.
Slope must be strong enough.
This is the strictest mode and generally provides the strongest chop rejection.
Either
Only one condition must pass.
This is more permissive:
A very clean slow trend may pass through efficiency.
A powerful but less orderly move may pass through slope.
It provides a balance between responsiveness and filtering.
Gate behavior
When the gate is open:
A new raw direction can update the trend state.
Bullish and bearish flips can be confirmed.
When the gate is closed:
The previous confirmed trend persists.
Attempted changes are blocked.
The display can dim, turn neutral, or hide.
This means the indicator behaves like a regime-holding system during chop.
It does not constantly reset to neutral. It retains the last confirmed direction until sufficient evidence supports a new one.
Blocked flips
A blocked flip occurs when:
The filtered line attempts to change direction.
The attempted direction differs from the confirmed trend.
The chop gate is closed.
The raw direction has just changed.
These can optionally be displayed as small X markers.
Blocked flips are useful because they show:
Where a basic slope indicator would have reversed.
Where the chop filter rejected that reversal.
How much signal noise the gate is removing.
They are not trade signals. They are diagnostic information.
Trend persistence
The trend variable is persistent.
Once bullish:
It remains bullish until a valid bearish change passes the gate.
Once bearish:
It remains bearish until a valid bullish change passes the gate.
This persistence is central to the design.
The indicator is not merely coloring every local slope. It is maintaining a confirmed market regime.
Display modes when the gate is closed
The indicator offers three ways to display gated conditions.
Dim
The current trend color remains visible but becomes transparent.
This communicates:
The last confirmed trend is still active.
Current conditions are not strong enough to confirm a new direction.
This is useful when you want regime continuity without overstating conviction.
Neutral
The trend line and candles switch to the selected gate color.
This communicates:
The directional regime is being withheld.
Current conditions are considered non-trending or uncertain.
Hide
The trend line disappears while the gate is closed.
This is the strictest visual mode.
It communicates:
No actionable trend state should be displayed during the gated condition.
Trend line coloring
The base color is determined by the confirmed trend:
Bullish trend uses the long color.
Bearish trend uses the short color.
Uninitialized state uses gray.
The gate display can then modify the final presentation.
This allows the chart to show:
Direction
Confirmation status
Chop-filter activity
without needing a separate panel.
Gradient fill
The indicator fills the area between price and the trend line.
When price is above the trend line:
A bullish gradient is displayed.
When price is below the trend line:
A bearish gradient is displayed.
The fill is stronger near the trend line and fades toward price.
This emphasizes the trend line as the structural reference.
The fill color follows the gate display state:
Full trend color when active
Dimmed during a closed gate in Dim mode
Neutral when configured
Hidden when the trend line is hidden
Trend glow
A soft glow is created around the filtered line using a small ATR-scaled distance.
The glow width is:
ATR(14) × 0.06
Using ATR ensures the glow remains visually proportional across assets and price scales.
The glow does not affect the calculation. It improves readability and reinforces the line as the central structural output.
Candle coloring
Candles can be colored using the confirmed trend state.
When the gate is open:
Bull trend produces bullish candles.
Bear trend produces bearish candles.
When the gate is closed:
Dim mode fades the existing trend color.
Neutral mode uses the gate color.
Hide mode removes the candle override.
This gives an immediate full-chart view of both trend and gate status.
Signal logic
Signals only occur when the confirmed trend changes.
Bullish flip
A bullish signal requires:
The active trend becomes bullish.
The previous trend was bearish.
The gate accepted the change.
Bearish flip
A bearish signal requires:
The active trend becomes bearish.
The previous trend was bullish.
The gate accepted the change.
This is more selective than simply detecting a change in line slope.
How to interpret the indicator
Bullish confirmed regime
A bullish regime means:
The median-filtered and low-pass-smoothed trend line is rising.
The move satisfied the selected chop-filter conditions when the regime changed.
The last accepted direction remains bullish.
Bearish confirmed regime
A bearish regime means:
The final trend line is falling.
The bearish change passed the selected quality gate.
The last accepted direction remains bearish.
Gate closed in an existing trend
This means:
The market is no longer moving with sufficient efficiency or slope.
A new reversal cannot currently be confirmed.
The previous regime remains stored.
This often occurs during:
Consolidation
Pullbacks
Low-volatility drift
Transition phases
Repeated blocked flips
Repeated blocked changes suggest:
The filtered line is oscillating.
Directional quality is weak.
A normal trend-following system would likely be whipsawing.
This is exactly the environment the gate is designed to avoid.
How to use it in practice
1. Directional regime filter
Use the confirmed trend to filter other setups:
Favor long trades during bullish regimes.
Favor short trades during bearish regimes.
Reduce activity when the gate is closed.
2. Trend-following entries
Bullish and bearish flips can be used as directional entry triggers, especially when confirmed by:
Price structure
Breakouts
Volume expansion
Higher-timeframe alignment
3. Pullback framework
During an established trend:
Price returning toward the trend line may represent a pullback.
If the gate remains closed but the trend does not flip, the move may be consolidation rather than reversal.
If the opposite direction eventually passes the gate, the regime has changed more meaningfully.
4. Chop avoidance
The most direct use is avoiding repeated entries during low-quality conditions.
When the display is dim, neutral, or hidden:
Reduce confidence in new trend signals.
Wait for efficiency or slope to recover.
5. Diagnostic comparison
Enable blocked flips to see how often the raw trend attempts to reverse without confirmation.
This helps tune:
Efficiency threshold
Slope threshold
Gate mode
Input guide
Source
Selects the price series used by the median cascade.
Close is the standard choice.
Alternatives such as hl2 or hlc3 may produce a slightly smoother structural input.
Cascade Stages
Controls how many median filters are used.
1: responsive
2: balanced
3: strongest noise rejection
Median Stage Lengths
Control the window used at each stage.
Shorter values:
Preserve responsiveness.
Remove only very short-duration noise.
Longer values:
Produce stronger structural filtering.
Delay shorter turns.
Low-Pass Length
Controls the two-pole Super Smoother.
Lower:
Faster
More reactive
Higher:
Smoother
More conservative
Direction Lookback
Controls how far back the current line is compared when determining raw direction.
Lower:
Faster slope changes
Higher:
More stable directional measurement
Efficiency Length
Controls the window used to measure net movement versus total path movement.
Shorter:
More responsive efficiency reading
More sensitive to recent chop
Longer:
More stable directional-quality assessment
Minimum Efficiency
Controls how clean the directional path must be.
Higher values make the gate stricter.
Slope Length
Controls the interval across which trend-line movement is measured.
Slope ATR Length
Controls the ATR baseline used to normalize slope.
Minimum ATR-Normalized Slope
Controls the minimum volatility-adjusted displacement required.
Higher values require stronger movement.
Tuning examples
Faster trend configuration
1 or 2 median stages
Short median windows
Lower Super Smoother length
Direction Lookback of 1 or 2
Either gate mode
Lower efficiency and slope thresholds
Balanced configuration
2 or 3 median stages
Progressive windows such as 3, 5, 7
Moderate Super Smoother length
Both gate mode
Moderate thresholds
Conservative configuration
3 stages
Longer median windows
Higher Super Smoother length
Longer Direction Lookback
Both gate mode
Higher minimum efficiency and slope
How this differs from a normal moving average
A standard moving average:
Uses linear averaging.
Responds directly to outlier magnitude.
Changes direction whenever its slope changes.
Median Cascade Trend:
Uses nonlinear outlier-resistant preprocessing.
Applies a proper recursive low-pass stage.
Separates raw direction from confirmed regime.
Blocks changes during inefficient or weak movement.
How this differs from a normal median filter
A basic median filter only removes impulse noise.
This indicator extends the idea by adding:
Multiple median stages
Low-pass smoothing
Direction measurement
Efficiency gating
Volatility-normalized slope gating
Persistent trend states
Signals and alerts
It is not simply a median-smoothed line. It is a complete trend-regime system built on median preprocessing.
How this differs from a Supertrend
A Supertrend uses ATR bands around price and changes state when price crosses the trailing boundary.
Median Cascade Trend does not use a volatility band to define direction.
Instead:
Direction comes from the slope of the filtered trend line.
ATR is used only to normalize slope and scale visuals.
Trend changes are controlled by movement quality rather than price crossing a stop band.
Strengths
Strong rejection of isolated price spikes
Preserves broader structural movement
Combines nonlinear and linear filtering
Separates raw turns from confirmed trend changes
Configurable chop rejection
Volatility-normalized slope testing
Persistent directional regimes
Blocked-flip diagnostics
Fully causal calculation
Limitations
Strong filtering can delay genuine reversals.
Long median windows may suppress shorter trend legs.
Strict gate settings can hold the previous regime too long.
Loose gate settings reduce the benefit of chop filtering.
Median filters can produce stepped transitions before low-pass smoothing.
The indicator remains reactive rather than predictive.
Best use cases
Median Cascade Trend is particularly suited for:
Trend filtering in noisy markets
Reducing false reversals caused by wicks
Swing-trading regime identification
Filtering entries from faster systems
Dynamic trend-structure visualization
Avoiding sideways-market whipsaws
It can be applied across:
Equities
Indices
Futures
Forex
Cryptocurrency
Commodities
Alerts
The indicator provides alerts for:
Confirmed bullish trend changes
Confirmed bearish trend changes
Trend changes blocked by the chop filter
The blocked-flip alert is especially useful for monitoring when the line attempts to reverse but market quality remains insufficient.
Summary
Median Cascade Trend is a multi-stage trend extraction system designed to reject impulsive market noise before determining direction. It first applies up to three causal median filters, progressively removing isolated spikes and short-duration disturbances. The cleaned series is then passed through a two-pole Super Smoother to extract a stable low-frequency trend line.
Rather than accepting every change in slope, the indicator evaluates the quality of the movement using directional efficiency and ATR-normalized slope. Depending on the selected gate mode, trend changes can require clean directional travel, sufficient volatility-adjusted displacement, or both.
This produces a persistent trend state that changes only when the filtered line turns and the surrounding movement is strong enough to justify the reversal. The final result is a robust trend-following framework that combines outlier rejection, low-pass smoothing, directional-quality measurement, and chop suppression into a single overlay.
אינדיקטור

Simple NIFTY Stochastic CE PE System PRAKASAN//@version=6
indicator(
title = "Simple NIFTY Stochastic CE PE System",
shorttitle = "Simple CE PE",
overlay = true
)
//--------------------------------------------------
// INPUTS
//--------------------------------------------------
stochLength = input.int(14, "Stochastic Length")
smoothK = input.int(3, "K Smoothing")
smoothD = input.int(3, "D Smoothing")
oversoldLevel = input.int(20, "Oversold Level")
overboughtLevel = input.int(80, "Overbought Level")
emaLength = input.int(20, "EMA Length")
useVWAP = input.bool(true, "Use VWAP Filter")
showEMA = input.bool(true, "Show EMA")
showVWAP = input.bool(true, "Show VWAP")
//--------------------------------------------------
// INDICATORS
//--------------------------------------------------
emaValue = ta.ema(close, emaLength)
vwapValue = ta.vwap(hlc3)
rawStoch = ta.stoch(close, high, low, stochLength)
stochK = ta.sma(rawStoch, smoothK)
stochD = ta.sma(stochK, smoothD)
//--------------------------------------------------
// TREND FILTER
//--------------------------------------------------
bullishTrend =
close > emaValue and
(not useVWAP or close > vwapValue)
bearishTrend =
close < emaValue and
(not useVWAP or close < vwapValue)
//--------------------------------------------------
// STOCHASTIC SIGNALS
//--------------------------------------------------
// Buy CE when Stochastic crosses upward from oversold
bullishSignal =
ta.crossover(stochK, stochD) and
stochK < 35 and
bullishTrend
// Buy PE when Stochastic crosses downward from overbought
bearishSignal =
ta.crossunder(stochK, stochD) and
stochK > 65 and
bearishTrend
//--------------------------------------------------
// TRADE STATE
//--------------------------------------------------
// 0 = waiting for CE
// 1 = CE active
// 2 = waiting for PE
// -1 = PE active
var int tradeState = 0
bool buyCE = false
bool exitCE = false
bool buyPE = false
bool exitPE = false
buyCE := false
exitCE := false
buyPE := false
exitPE := false
//--------------------------------------------------
// SIGNAL SEQUENCE
//--------------------------------------------------
// Step 1: Buy CE
if tradeState == 0 and bullishSignal
buyCE := true
tradeState := 1
// Step 2: Exit CE
if tradeState == 1 and bearishSignal
exitCE := true
tradeState := 2
// Step 3: Generate fresh Buy PE signal
else if tradeState == 2 and bearishSignal
buyPE := true
tradeState := -1
// Step 4: Exit PE
if tradeState == -1 and bullishSignal
exitPE := true
tradeState := 0
//--------------------------------------------------
// CHART SIGNALS
//--------------------------------------------------
plotshape(
buyCE,
title = "BUY CE",
text = "BUY CE",
style = shape.labelup,
location = location.belowbar,
color = color.green,
textcolor = color.white,
size = size.small
)
plotshape(
exitCE,
title = "EXIT CE",
text = "EXIT CE",
style = shape.labeldown,
location = location.abovebar,
color = color.orange,
textcolor = color.white,
size = size.small
)
plotshape(
buyPE,
title = "BUY PE",
text = "BUY PE",
style = shape.labeldown,
location = location.abovebar,
color = color.red,
textcolor = color.white,
size = size.small
)
plotshape(
exitPE,
title = "EXIT PE",
text = "EXIT PE",
style = shape.labelup,
location = location.belowbar,
color = color.blue,
textcolor = color.white,
size = size.small
)
//--------------------------------------------------
// INDICATOR LINES
//--------------------------------------------------
plot(
showEMA ? emaValue : na,
title = "EMA",
color = color.orange,
linewidth = 2
)
plot(
showVWAP ? vwapValue : na,
title = "VWAP",
color = color.purple,
linewidth = 2
)
//--------------------------------------------------
// ALERTS
//--------------------------------------------------
alertcondition(
buyCE,
title = "BUY CE Alert",
message = "BUY CE signal generated."
)
alertcondition(
exitCE,
title = "EXIT CE Alert",
message = "EXIT CE signal generated."
)
alertcondition(
buyPE,
title = "BUY PE Alert",
message = "BUY PE signal generated."
)
alertcondition(
exitPE,
title = "EXIT PE Alert",
message = "EXIT PE signal generated."
) אינדיקטור

ABC/D
Every bar gets a direction (up/down) from higher-highs/lower-lows — these build the Gann ZigZag legs.
Consecutive bars trapped inside a prior bar's range = Inside Bar ("Hoagie"); a second mini-ZigZag runs inside it.
U-Turn engine watches legs: trend flips only when price breaks the confirm level → defines trendDir.
ABC = 3-leg pullback in confirmed trend (A extreme > B extreme, C shallower) → continuation signal at C.
Variants: E-ABC (no U-Turn yet, pre-A pivot beyond C), L-ABC (late, after U-Turn), EQ-ABC (tick-equal A/B extremes).
I-prefix = same pattern found on the inner ZigZag, fully inside one Inside Bar (I-ABC, I-EQ-ABC…).
I-B-ABC = the Inside Bar itself IS the hidden B-leg between main legs A and C; E-I-B version = early variant.
ABCD = 4 nested shrinking legs in trend direction → signal at D.
Market structure: every ZigZag pivot stored as a level; close-through = BOS (or CHoCH if trend flips), wick-only = Sweep.
Multi-level: one candle breaking several stored levels fires one signal per level, on the exact breaker bar.
Same structure engine runs inside each Inside Bar → I-BOS / I-CHoCH / I-Sweep / I-U-Turn.
Flags: after an impulse pole, pivots A→B→A2→B2; ASC = HH+HL (bullish), DSC = mirror, BRD = expanding range.
Quad Stochastic: 4 stochastics aligned ≥80/≤20 shade background (extreme/capitulation zones + gap counters in table).
No60 model (optional): counter-bar + EMA filter entry arrows with confirmation dots.
Info table shows multi-TF trend grid, last ABC/ABCD details, Quad rotation stats. אינדיקטור
