Indicatore
Indicatori e strategie
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.
Indicatore
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.
Indicatore
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.
Indicatore
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.
Indicatore
Quick LevelsNothing terribly exciting, just does what it says on the tin. I wanted to be able to quickly get manual levels on my chart without having to draw a bunch of individual lines; this script is the result.
Indicatore
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で将来位置へ描画したもので、未来データを取得していません。現在価格との関係には、現在バー上に実際に整列している過去計算の先行スパンを使用します。
薄化点は右側に指定本数の確定バーを必要とするため、認識に意図的な遅延があります。初期設定では確認可能になったバーより左側へ表示しません。任意設定で元の投影位置へ表示する場合も、認識自体は確認後です。
未確定リアルタイムバーでは、高値・安値・終値の更新に伴い、転換線、基準線、先行スパン、雲の透明度、拡大・収縮状態が終値確定まで変化する場合があります。将来ラベルは初期設定で確定値を使用し、用意したアラートは確定足で判定します。
本インジケーターは研究・可視化ツールです。売買指示、将来予測、目標価格、損切り、ポジションサイズ、成績統計、投資助言を提供しません。厚い雲を必ず強い支持抵抗、薄い雲や収縮中の雲を必ずブレイクする状態とは定義していません。
Indicatore
RS Scalping Hellow Every One This Indicator For Buy and Sell signal Based On SuperTrend + EMA50 + RSI Signals
Indicatore
HTB Daddy Of Them AllHits Bankai v6
Gives you daily bias by color of clouds
Also gives you prime scalping opportunities by color of clounds
Indicators for Long/Shorts
Indicatore
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")
Indicatore
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.
Indicatore
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.
Indicatore
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."
)
Indicatore
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.
Indicatore
NSE Index Membership & MF holdingsTells you the script is part of which index and how popular is the script with the mutual funds.
Indicatore
High-Confidence Support & ResistanceStrong touch point pivotal areas with historical data. Only plots support and resistance area with 15 or more touching points near key market structure. It will only plot a pivot line with 3 confluences.
1.15 or more touch points.
2. near market structure.
3. in confluence with volume profiles.
Indicatore
Dow Theory Market Structure StrategyDow Theory Market Structure Strategy turns the classic "trade with rising highs and rising lows" rule into a fully mechanical, backtestable system, so the claim can be checked with data instead of taken on faith.
How it works
Structure: an uptrend is confirmed when the two most recent confirmed swing highs and swing lows are both rising (higher high & higher low). A downtrend is the mirror case. The trend is invalidated the moment price closes back through the most recent confirmed swing low (uptrend) / swing high (downtrend).
Swing detection: standard bar-pivot method (Depth bars required on each side). Every swing used is confirmed before use — nothing is plotted or traded ahead of confirmation, so the script does not repaint.
Entry (selectable): "Breakout" (default) enters on a close beyond the confirmed swing extreme once the higher-high/higher-low structure is in place. "Pullback" instead waits for price to retrace part of the most recent swing range and close back through that level before entering.
Exit (single line used for both stop-loss and take-profit — no separate profit target): "Low-break" (default) trails the latest confirmed swing low/high. "ATR" (selectable) instead trails a fixed ATR multiple from entry. There is no own-data evidence yet that the ATR mode outperforms the default — it is offered for side-by-side comparison, not because it has been shown to be better.
Position size: fixed notional = Margin input × Leverage input (defaults: 1,000,000 × 5 = 5,000,000, account currency), independent of running equity.
Adjustable inputs: Depth (swing sensitivity) · Entry mode (Breakout / Pullback) · Exit mode (Low-break / ATR) · Margin · Leverage.
Backtest disclosure (default settings — Depth=3, Breakout entry, Low-break exit; OANDA:USDJPY, 1H; 2023-01-05 – 2026-07-11; 343 closed trades; commission 0.01% per side):
Win rate 36.4% | Profit factor 1.15 | Net profit +430,456 (+43.05% on 1,000,000 initial capital) | Max drawdown -338,991 (-26.48%).
Long trades alone: 204 trades, 40.2% win rate, PF 1.35. Short trades alone: 139 trades, 30.9% win rate, PF 0.97 (a loser on its own over this period).
This is a single symbol, single period, single parameter set — it has not been reproduced across other pairs, timeframes, or Depth values. A -26.48% drawdown is large relative to the margin/leverage settings above; at these defaults it would approach margin-call territory in live use. This script is an educational verification tool from an ongoing public research project comparing implementations of Dow Theory — it is not a proven trading edge. Past performance does not guarantee future results. Nothing here is investment advice.
「ダウ理論 Market Structure Strategy」は、「高値・安値の切り上げに順張りする」というダウ理論の考え方を、誰でも検証できる完全に機械的なルールに落とし込んだストラテジーです。
仕組み
構造判定:直近2つの確定スイング高値・安値がともに切り上がっていれば上昇トレンド成立(下降はその逆)。終値が直近確定安値を割った時点(上昇の場合)でトレンド無効化。
スイング検出:前後Depth本のピボットで検出。使用するスイングはすべて確定済みのみで、リペイントしない。
エントリー(選択式):「突破」(既定)=構造成立後、確定した直近高値/安値を終値で改めて抜けた瞬間。「押し目」=直近スイングの値幅を一定割合戻したのち、その水準を終値で回復した瞬間。
撤退ライン(利確・損切りを分けず単一のラインで判定・選択式):「安値割れ」(既定)=直近確定安値/高値に追従。「ATR」=エントリー時のATR×倍率を初期距離としてトレール。自社データでATRが安値割れ方式を上回るという確認はまだ取れていないため、優劣を見比べるための選択肢として用意している。
建玉サイズ:証拠金入力×レバレッジ入力の固定金額(既定:100万円×5倍=500万円)。運用中の損益に連動しない。
変更できる項目:Depth(スイング感度)/エントリー方式/撤退ライン方式/証拠金/レバレッジ
バックテスト開示(既定設定=Depth3・突破・安値割れ/OANDA:USDJPY・1時間足/2023-01-05〜2026-07-11・確定343トレード/手数料0.01%片道):
勝率36.4%|プロフィットファクター1.15|純損益+430,456円(初期資金100万円に対し+43.05%)|最大ドローダウン▲338,991円(▲26.48%)。
ロング単体:204件・勝率40.2%・PF1.35。ショート単体:139件・勝率30.9%・PF0.97(単体では負け越し)。
この結果は単一通貨ペア・単一期間・単一パラメータでの1本の記録であり、他の通貨ペア・時間足・Depth値での再現性は未確認です。最大ドローダウン▲26.48%は上記の証拠金・レバレッジ設定に対して重く、この設定のまま実運用すればロスカット水域に近づく規模です。本スクリプトはダウ理論の実装比較を行う公開検証プロジェクトの一環としての教育・検証目的のツールであり、確立された優位性を示すものではありません。過去の成績は将来の成績を保証しません。投資助言ではありません。
Strategia
Flow Pair Decision Engine v2.0This is for my home who needs some help figuring these things out. I gotchu
Indicatore
ATSYS_KEEP_IT_SIMPLEATSYS_KEEP_IT_SIMPLE · OPEN CODE
Desenvolvido por ATSYSTEM - FABIO MAISTRO - @FABIONESTRADER
Pine Script v6 - TradingView
Versão: v2026_07_3_4 - Data: 10/07/2026
Publicação: OPEN CODE — para a comunidade TradingView (esta versão é PÚBLICA · código aberto por decisão colaborativa do autor)
================================================================
Este indicador tem como objetivo principal determinar qual a força dominante no mercado a cada candle através de sua nuvem de MME e seu código de cores intuitivo. As bandas ajudam a ler se a volatilidade está em expansão ou em contração. A variação de espessura da linha da média mais curta avisa se a tendencia existe e se ela está ganhando força ou não.
Leitura simplificada de estrutura e direção em um único indicador:
· Bandas de Bollinger (período 21 · desvio 2.0 · média exponencial) com nuvem azul entre elas — o "território" do preço.
· Média exponencial curta (13) — espessura aumenta quando a tendência ganha força.
· Média exponencial longa (34) — oculta por padrão (ligável).
· Nuvem entre as médias na cor do estado atual do mercado.
· Sinais "+" de clímax: verde acima do candle (força máxima de alta, quando some o sinal é uma possível exaustão de alta), vermelho abaixo (força máxima de baixa, quando some o sinal é uma possível exaustão de baixa).
COMO LER AS CORES (estado do mercado · médias e nuvem):
VERDE → alta plena (preço acima da média 13 · 13 acima da 34)
AZUL → pullback na alta (preço abaixo da 13 · 13 acima da 34)
CINZA → neutro / transição
ROXO → pullback na baixa (preço acima da 13 · 13 abaixo da 34)
VERMELHO→ queda plena (preço abaixo da 13 · 13 abaixo da 34)
================================================================
Suce$$o a todos,
Fabio Maistro
Indicatore
SESSIONS BY RIZ FXIt automatically shades the background of your chart for Asia, London, NY Morning, and NY Evening sessions (set to India time by default).
When a session ends, it shoots out dashed lines from the highest and lowest points of that session.
Traders use these lines to spot breakout levels and liquidity traps.
2. Shows a "Picture-in-Picture" of the Big Picture Trend
On the far right side of your screen, it floats a mini-display of the last 3 candles from a higher timeframe (like the 4-Hour chart).
It shows the wicks, the bodies, and labels the timeframe automatically.
This lets you track the larger market trend without constantly switching tabs or charts.
In short: It keeps you locked into daily timing zones while showing you what the big-money players are doing on the higher timeframes—all on a single screen.
Indicatore
Flow-State Publisher v2.0IYKYK
This is for my dearest friend to backtest and see if it works. Enjoy the heavily bogged down script and its many companions to follow
Indicatore
Institutional Sniper Signal (Clean v7)This indicator is a Multi-Timeframe (MTF) quantitative system designed to trade pullbacks and breakouts in alignment with the higher timeframe macro trend.
Rather than relying on a single indicator to dictate the trend, this script utilizes a Consensus Voting Mashup. By aggregating data from 15 different structural and momentum indicators on a higher timeframe, it calculates a definitive directional bias, filtering out the noise of ranging markets.
⚙️ CORE MECHANICS (The Consensus Logic):
To avoid repainting and false signals, the script operates in three strict phases:
The Macro Consensus (4H Closed Candle): The engine pulls data from the last closed 4H candle across 15 distinct tools (including EMA 200, EMA 50, WMA 100, Parabolic SAR, Ichimoku Tenkan/Kijun, DEMA, TEMA, and standard deviation bands). Each indicator gets 1 "vote" (Buy or Sell). A trade is only authorized if a strict user-defined threshold is met (e.g., 10 out of 15 indicators agreeing on the same direction).
The Pullback Trigger (1H): Once the macro consensus is formed, the script monitors the 1H timeframe. It waits for the local price to retrace and touch the 1H 20 EMA, identifying a potential discounted entry area.
The Fractal Breakout (Execution): It does not enter at market price. Instead, it calculates a 5-bar Fractal High (for longs) or Fractal Low (for shorts). It then plots visual pending order lines (Buy Stop / Sell Stop) at these fractal extremes, adding a customizable price offset to avoid fakeouts.
🛡️ RISK MANAGEMENT:
ATR Stop Loss: The stop loss is dynamically plotted at the opposite fractal, buffered by an ATR multiplier to allow the trade to breathe.
Daily Limit: Includes a daily signal limiter to prevent overtrading during high-volatility sideways days.
🛠️ HOW TO USE:
Apply the script to your execution timeframe (e.g., 15m or 30m). Adjust the "Offset" input based on your asset (e.g., 0.0002 for Forex pairs or 2.0 for US Indices). When a valid consensus is met and the price pulls back, the indicator will plot horizontal lines with precise labels for your pending Entry and Stop Loss.
🇧🇷 (PORTUGUÊS)
Este indicador é um sistema quantitativo Multi-Timeframe (MTF) projetado para operar pullbacks e rompimentos alinhados com a tendência macro.
Em vez de usar apenas um indicador para definir a tendência, este script utiliza um Sistema de Votação por Consenso. Ele agrega dados de 15 indicadores diferentes no tempo gráfico maior para calcular um viés direcional definitivo.
⚙️ COMO FUNCIONA A LÓGICA:
Para evitar repintura (repainting), o script opera em 3 fases:
O Consenso Macro (Vela Fechada H4): O motor puxa os dados da última vela fechada de H4 em 15 ferramentas diferentes (EMA 200, Ichimoku, DEMA, SAR, etc). Cada indicador dá 1 "voto". O setup só é armado se a maioria esmagadora (ex: 10 de 15) concordar com a direção.
O Gatilho de Pullback (H1): Com o consenso formado, o script espera o preço retrair e tocar na EMA 20 do H1 (área de desconto).
O Rompimento do Fractal (Entrada): O indicador não entra a mercado. Ele mapeia a Máxima ou Mínima dos últimos 5 candles (Fractal) e desenha uma linha de ordem pendente (Buy Stop / Sell Stop) com um recuo (offset) customizável.
COMO USAR: Adicione no seu gráfico de execução (ex: M15). Ajuste o valor do "Offset" nas configurações de acordo com o ativo (ex: digite 0.0002 se for Forex ou 2.0 se for Índice). Aguarde as linhas de entrada e Stop Loss aparecerem na tela para posicionar suas ordens pendentes.
Indicatore
Institutional Sniper Signal (Clean v7)This indicator is a Multi-Timeframe (MTF) quantitative system designed to trade pullbacks and breakouts in alignment with the higher timeframe macro trend.
Rather than relying on a single indicator to dictate the trend, this script utilizes a Consensus Voting Mashup. By aggregating data from 15 different structural and momentum indicators on a higher timeframe, it calculates a definitive directional bias, filtering out the noise of ranging markets.
⚙️ CORE MECHANICS (The Consensus Logic):
To avoid repainting and false signals, the script operates in three strict phases:
The Macro Consensus (4H Closed Candle): The engine pulls data from the last closed 4H candle across 15 distinct tools (including EMA 200, EMA 50, WMA 100, Parabolic SAR, Ichimoku Tenkan/Kijun, DEMA, TEMA, and standard deviation bands). Each indicator gets 1 "vote" (Buy or Sell). A trade is only authorized if a strict user-defined threshold is met (e.g., 10 out of 15 indicators agreeing on the same direction).
The Pullback Trigger (1H): Once the macro consensus is formed, the script monitors the 1H timeframe. It waits for the local price to retrace and touch the 1H 20 EMA, identifying a potential discounted entry area.
The Fractal Breakout (Execution): It does not enter at market price. Instead, it calculates a 5-bar Fractal High (for longs) or Fractal Low (for shorts). It then plots visual pending order lines (Buy Stop / Sell Stop) at these fractal extremes, adding a customizable price offset to avoid fakeouts.
🛡️ RISK MANAGEMENT:
ATR Stop Loss: The stop loss is dynamically plotted at the opposite fractal, buffered by an ATR multiplier to allow the trade to breathe.
Daily Limit: Includes a daily signal limiter to prevent overtrading during high-volatility sideways days.
🛠️ HOW TO USE:
Apply the script to your execution timeframe (e.g., 15m or 30m). Adjust the "Offset" input based on your asset (e.g., 0.0002 for Forex pairs or 2.0 for US Indices). When a valid consensus is met and the price pulls back, the indicator will plot horizontal lines with precise labels for your pending Entry and Stop Loss.
🇧🇷 (PORTUGUÊS)
Este indicador é um sistema quantitativo Multi-Timeframe (MTF) projetado para operar pullbacks e rompimentos alinhados com a tendência macro.
Em vez de usar apenas um indicador para definir a tendência, este script utiliza um Sistema de Votação por Consenso. Ele agrega dados de 15 indicadores diferentes no tempo gráfico maior para calcular um viés direcional definitivo.
⚙️ COMO FUNCIONA A LÓGICA:
Para evitar repintura (repainting), o script opera em 3 fases:
O Consenso Macro (Vela Fechada H4): O motor puxa os dados da última vela fechada de H4 em 15 ferramentas diferentes (EMA 200, Ichimoku, DEMA, SAR, etc). Cada indicador dá 1 "voto". O setup só é armado se a maioria esmagadora (ex: 10 de 15) concordar com a direção.
O Gatilho de Pullback (H1): Com o consenso formado, o script espera o preço retrair e tocar na EMA 20 do H1 (área de desconto).
O Rompimento do Fractal (Entrada): O indicador não entra a mercado. Ele mapeia a Máxima ou Mínima dos últimos 5 candles (Fractal) e desenha uma linha de ordem pendente (Buy Stop / Sell Stop) com um recuo (offset) customizável.
COMO USAR: Adicione no seu gráfico de execução (ex: M15). Ajuste o valor do "Offset" nas configurações de acordo com o ativo (ex: digite 0.0002 se for Forex ou 2.0 se for Índice). Aguarde as linhas de entrada e Stop Loss aparecerem na tela para posicionar suas ordens pendentes.
Indicatore






















