อินดิเคเตอร์

Variance-Weighted Regression Trend [BackQuant]Variance-Weighted Regression Trend
Overview
Variance-Weighted Regression Trend is a rolling linear-regression trend indicator that adjusts the influence of observations according to the estimated variance of their regression residuals.
The script first calculates a standard ordinary least-squares regression across the selected window. It then measures the squared residuals around that fit and uses those residuals to estimate how variable the regression error has been through the sample.
Those variance estimates are converted into relative weights. Lower estimated residual variance can receive more influence, while higher estimated residual variance can receive less. A second weighted regression is then calculated using those weights.
The indicator also includes:
EMA, RMA or rolling-average residual variance.
Configurable inverse-variance weighting strength.
Weight regularization and upper/lower weight limits.
Weighted R² and slope-quality diagnostics.
Two regression-channel methods.
Optional trend-flip quality confirmation.
OLS comparison.
Linear regression projection.
Trend colouring and alerts.
Calculation
The basic process is:
Fit an ordinary least-squares regression over the Regression Length.
Calculate the squared residual of every observation around that fit.
Smooth those squared residuals to estimate local residual variance.
Add a regularization floor to reduce unstable extreme weights.
Convert variance into relative observation weights.
Clamp weights between the selected minimum and maximum.
Calculate a second weighted regression.
The weighted line is therefore influenced more by observations receiving larger relative weights and less by those receiving smaller ones.
Variance Weighting
The weighting is based on regression residual variance , not ATR, trading volume or raw price volatility.
For each point:
Residual = Source - OLS fitted value
Squared Residual = Residual²
The squared residuals are then processed using the selected Variance Model.
EMA
Uses exponential smoothing and responds more quickly to recent residual changes.
RMA
Uses a slower recursive smoothing process.
Rolling Mean
Uses a finite moving average of squared residuals.
Weight Power
Weight Power controls how strongly estimated variance affects the regression.
The raw weighting relationship is:
Weight ∝ 1 / Variance^Weight Power
0 gives equal weighting, making the final fit behave like the OLS regression.
1 applies standard inverse-variance-style weighting.
Values above 1 increase the difference between low- and high-variance observations.
Higher settings can make the regression more selective, but can also concentrate too much influence in a small part of the sample.
Variance Regularization
Very small variance estimates can otherwise create extremely large inverse weights.
The script therefore adds a fraction of the window's mean squared residual to each local variance estimate.
Higher regularization makes the weights more uniform.
Lower regularization allows stronger differences between observations.
Minimum and Maximum Relative Weight
Raw weights are normalized relative to their average before being clamped.
A relative weight above 1 means the observation has greater-than-average influence.
A value below 1 means it has less.
The Minimum Relative Weight prevents high-variance observations from effectively disappearing from the regression.
The Maximum Relative Weight prevents very low-variance observations from dominating the entire fit.
Weighted Regression
Once the final weights are calculated, the script solves a weighted linear regression:
Y = Intercept + Slope × X
The displayed line is the current endpoint of that rolling weighted regression.
Each new bar shifts the regression window and recalculates:
OLS.
Residuals.
Variance estimates.
Weights.
Weighted slope and intercept.
OLS Comparison
The optional OLS line shows the endpoint of the initial equal-weight regression.
This makes it easy to see how much the variance weighting is actually changing the result.
If Weight Power is set to 0, the weighted regression and OLS should be effectively aligned.
As the weighting becomes more aggressive, the lines may separate depending on the residual structure inside the window.
Trend State
Trend direction comes from the sign of the weighted regression slope.
Positive slope = bullish.
Negative slope = bearish.
A bullish flip occurs when the stored trend changes from bearish to bullish.
A bearish flip occurs when it changes from bullish to bearish.
Quality Confirmation
Quality Confirmation can be enabled to prevent weak slope changes from immediately flipping the trend state.
When enabled, an opposite slope must also satisfy:
Minimum Weighted R².
Minimum Slope / Standard Error.
If those conditions are not met, the existing trend state remains active even if the current slope temporarily changes sign.
Weighted R²
Weighted R² measures how well the weighted straight-line regression describes the current sample.
Higher values indicate that the weighted observations are more closely aligned with a linear fit.
Lower values indicate a less orderly linear relationship.
R² does not determine trend direction and should not be interpreted as a forecast of future performance.
Slope / Standard Error
The script calculates the absolute weighted slope relative to its estimated standard error:
|Slope| / Slope Standard Error
This is used as a practical slope-quality measure.
Higher values indicate that the fitted slope is larger relative to the estimated regression error.
It is used by the optional Quality Confirmation setting and is not presented as a formal significance test.
Regression Channels
Two channel-width methods are available.
Weighted Residual RMS
Uses the weighted root-mean-square distance of observations from the fitted regression.
This reflects the general amount of scatter around the line.
Regression Standard Error
Uses the calculated standard error of the fitted current regression value.
This normally represents a different and often narrower measure than residual RMS.
The Channel Multiplier scales whichever method is selected.
Expand During Poor Fit
When enabled, the channel becomes wider as Weighted R² decreases.
This is intended to visually reflect greater uncertainty when the current window is poorly described by a straight line.
The expansion affects only the channel width.
It does not alter the regression or trend calculation.
Projection
The Projection extends the current regression slope forward by the selected number of bars.
It is simply:
Current fitted line extended using the current slope.
It is not a separate forecasting model.
As the regression changes on new bars, the projection also changes.
Current Relative Weight
The Data Window shows the final relative weight assigned to the newest observation.
A value:
Above 1 = greater-than-average influence.
Below 1 = less-than-average influence.
This can help show how the current observation is being treated by the variance-weighting model.
Effective Sample Size
The indicator also reports:
Effective N = (Sum of Weights)² / Sum of Squared Weights
This provides a simple measure of weight concentration.
If weights are similar, Effective N remains close to the full Regression Length.
If a smaller group of observations receives most of the weight, Effective N falls.
This is useful when experimenting with aggressive Weight Power or wide weight limits.
Trend Strength
Trend Strength is used only for the regression glow.
It combines:
60% Weighted R².
40% normalized Slope / Standard Error.
It does not affect the regression or signals.
ATR(14) is used only to scale the visual width of the glow and flip bloom to the instrument.
Input Guide
Regression Length
Controls the size of the rolling regression sample.
Projection Bars
Controls how far the current fitted slope is extended visually.
Variance Length
Controls how quickly the residual-variance estimate changes.
Variance Model
Selects EMA, RMA or Rolling Mean smoothing of squared residuals.
Weight Power
Controls the strength of inverse-variance weighting.
Variance Regularization
Reduces extreme differences between weights.
Minimum / Maximum Relative Weight
Limits how little or how much influence any one observation can receive.
Channel Width
Selects Weighted Residual RMS or Regression Standard Error.
Channel Multiplier
Scales the regression channel.
Poor Fit Expansion
Optionally widens the channel as R² deteriorates.
Quality Confirmation
Requires minimum regression fit and slope quality before allowing trend flips.
How to use it
The indicator can be used as:
A regression-based trend filter.
A comparison between ordinary and variance-weighted regression.
A way to study how residual-based weighting changes a rolling trend estimate.
A trend-quality filter using R² and slope strength.
A regression channel for visualizing fit dispersion.
The OLS Comparison and Data Window values are particularly useful when testing the weighting settings, because they show whether the extra weighting is materially changing the regression or simply producing a result close to ordinary least squares.
Limitations
The variance estimates are derived from OLS residuals inside the same rolling window.
The model is a custom two-stage weighted regression rather than a full generalized least-squares procedure.
Higher Weight Power can concentrate the fit in a relatively small part of the sample.
Linear regression cannot represent every type of market structure.
High R² does not imply future trend continuation.
The forward projection is only a linear extrapolation of the current fit.
Quality Confirmation can reduce weak flips but can also delay genuine changes in direction.
Data Window
The script exposes:
Weighted Slope.
Weighted R².
Slope / Standard Error.
Weighted Residual RMS.
Regression Standard Error.
Current Relative Weight.
Effective Sample Size.
Trend Strength.
Alerts
The indicator includes:
Variance-Weighted Regression Bullish: trend changes from bearish to bullish.
Variance-Weighted Regression Bearish: trend changes from bullish to bearish.
Variance-Weighted Regression Flip: either transition occurs.
Summary
Variance-Weighted Regression Trend starts with a normal rolling OLS regression, measures the residual variance around that fit, and uses those estimates to assign relative weights to the observations in a second regression.
The weighting strength, variance smoothing, regularization and weight limits are all configurable, making it possible to move from essentially equal-weight OLS to a much more selective fit.
The final weighted slope controls the trend state, while Weighted R² and the Slope / Standard Error score can optionally be used to filter weak reversals.
Regression channels, OLS comparison, forward projection and the visual strength system provide additional context around the core weighted regression without changing the underlying trend logic.
อินดิเคเตอร์

Reversal OB ZonesREVERSAL OB ZONES
Reversal OB Zones locates the first Break of Structure in a trend and marks the Order Block and rebound zone that come with it - one setup at a time, drawn the moment the break confirms, using only price structure that already exists on the chart.
THE IDEA BEHIND IT
The indicator is built on the Smart Money Concepts / ICT idea that a trend doesn't reverse randomly: it reverses at the last point where "smart money" was still positioned in the direction of the old trend before structure broke. That point is the Order Block - the last opposing candle before the move that produced the reversal - and it tends to act as support or resistance the first time price returns to it.
To find that moment, the script tracks a trailing key level: the support (in an uptrend) or resistance (in a downtrend) left behind by the most recent genuine higher high or lower low. A pullback that doesn't make a new extreme never moves this level - only an actual new high or low does. The first candle to close back through that level is the first Break of Structure (BOS). Everything else - the Order Block and the rebound zone - is already sitting in the chart's history at that exact moment, so both are drawn immediately, on the same candle as the break, with no repainting and no waiting for future bars to "confirm" anything further.
Swing highs and lows themselves come from a pure, zero-threshold structure detector (a point counts the moment the next candle confirms it was a local extreme) - there is no ATR filter or fixed lookback window involved, so the logic behaves the same in quiet and in noisy price action.
WHAT'S ON THE CHART
Each setup is made of three parts, always drawn together:
- First BOS line and label: marks the level that broke and the candle that broke it.
- Order Block zone (teal for longs, maroon for shorts): the last opposite-colored candle before the trend's real high/low, with a small ATR buffer added beyond that extreme.
- Rebound zone (gray box): the two prior structural support/resistance levels immediately behind the Order Block. This is the room price is expected to use while retracing back up (or down) into the Order Block; it is not a level to be traded on its own - see below.
Only one setup is ever active at a time: while an Order Block and its rebound zone are on the chart, the indicator will not flag a new BOS in either direction. A setup stays on the chart until it is invalidated - there is no time-based expiry.
HOW TO USE IT
The Order Block is the only zone you trade. A bearish (maroon) Order Block is a level to look for shorts; a bullish (teal) Order Block is a level to look for longs - the trade direction always matches the color of the Order Block, not the gray zone.
The gray rebound zone is not tradable. It exists purely to define how far price is allowed to retrace before the setup is considered dead: it marks the boundary between "price is still reasonably retracing toward the Order Block" and "price has gone too far and the level no longer means anything." It is a boundary, not an entry.
A setup is invalidated - and both zones disappear together - under exactly two conditions:
1. Price closes back through the far side of the Order Block (the old trend has genuinely resumed).
2. Price closes through the far side of the gray rebound zone (support/resistance failed with no bounce, so the Order Block is no longer valid either).
If neither happens, the zones simply stay on the chart - there's no bar-count expiry to worry about.
A practical read: wait for the BOS, then watch for price to retrace back into the Order Block zone. The gray zone underneath (or above, for longs) is your line in the sand - if price closes beyond it before ever tagging the Order Block, treat the setup as invalidated rather than waiting for a reaction that structurally shouldn't be expected anymore.
INPUTS
- Look for bearish / bullish setups: enable or disable each direction independently.
- Order Block lookback: how many bars back to search for the Order Block candle.
- Pivot history to remember: how many structural key levels to keep for rebound-zone lookups.
- ATR length / buffer: controls the small buffer added beyond the Order Block's originating extreme.
- Style: colors and label size for both zones and the BOS marker.
NOTES
Because everything is built from confirmed structure rather than fixed-length pivots or volatility thresholds, the indicator works the same way across instruments and timeframes without needing to be re-tuned. As with any structural/SMC tool, treat it as a way to frame where price is likely to react, not as a standalone signal - combine it with your own confirmation and risk management. อินดิเคเตอร์

Regression Slope Oscillator [QuantAlgo]🟢 Overview
The Regression Slope Oscillator measures the rate of directional change in price using a robust regression estimator that resists outliers, then converts that slope into a scale free reading so a single threshold carries the same meaning across instruments and timeframes. Rather than fitting a least squares line, which a single spike or gap can pull off course, it takes the median of pairwise slopes inside a rolling window to produce a trend estimate that holds up through erratic data. A three state engine with separate entry and exit thresholds then translates the normalized slope into a bullish, bearish, or neutral regime, holding established states through pullbacks instead of flickering whenever the reading brushes the boundary.
🟢 How It Works
The indicator's core methodology lies in its combination of outlier resistant slope estimation and volatility relative normalization, where a trend regime is only established once the fitted rate of change clears a threshold expressed in units of the instrument's own volatility.
First, the source is optionally moved into log space so the fitted slope becomes a proportional rate of change rather than an absolute one, keeping readings comparable across instruments at very different price levels and across histories where price has moved by an order of magnitude:
srcMid = useLog ? math.log(srcSafe) : srcInput
Then the slope is fitted across the window using a robust estimator rather than ordinary least squares, which has an effective breakdown point of zero and lets a single gap or liquidation wick tilt the fit for the entire window. Theil-Sen takes the median of every pairwise slope inside the window, tolerating roughly 29 percent contaminated data while staying close to a least squares fit on clean data:
for i = 0 to length - 2 by 1
for j = i + 1 to length - 1 by 1
array.push(slopes, (source - source ) / (j - i))
array.median(slopes)
Repeated Median nests the same idea, taking a median of pairwise slopes anchored on each bar and then a median of those results, which lifts the breakdown point to 50 percent, the theoretical maximum, at several times the computational cost. Both estimators target the same underlying quantity, so switching between them changes robustness without shifting the scale.
The raw slope is then divided by a volatility unit to strip out the instrument's price scale and volatility regime, producing a reading that means the same thing on any chart:
normUnit = switch normMode
'ATR' => useLog ? atrUnit / srcSafe : atrUnit
'Stdev' => sdevUnit
=> useLog ? 0.01 : srcSafe / 100.0
slope = rawMid / normUnit
Each path is dimensionally self consistent with the log transform, so numerator and denominator always move together and the resulting reading stays dimensionless. In ATR mode a value of 0.10 means the trend is advancing at one tenth of an average true range per bar.
The normalized slope then drives a state engine where the level required to establish a regime and the level required to release it are deliberately different, creating a hysteresis band that suppresses boundary flicker:
if slope > entryTh
state := 1
else if slope < -entryTh
state := -1
else if useNeutral and state == 1 and slope < exitTh
state := 0
else if useNeutral and state == -1 and slope > -exitTh
state := 0
Finally, in Candles display mode the estimator runs two additional passes against the chart high and the chart low, building a synthetic OHLC series in slope space where the body spans the change in slope and the wicks reveal how far trend disperses across the bar range, with an optional Heikin-Ashi transform applied on top:
barHigh = math.max(slopeHigh, math.max(barOpen, barClose))
barLow = math.min(slopeLow, math.min(barOpen, barClose))
haClose = math.avg(barOpen, barHigh, barLow, barClose)
🟢 Signal Interpretation
▶ Bullish State (Oscillator Above the Upper Entry Band with Bullish Color)
The normalized slope has cleared the positive entry threshold, meaning price is advancing faster than the instrument's own recent volatility rather than simply drifting higher. Trend traders take the confirmation as a long entry and hold through pullbacks, since the state only releases once the slope retreats below the exit level rather than on every minor pause, and a reading that climbs deeper into the upper zones represents strengthening rather than a reason to exit. Mean reversion traders read the same plot for depth instead of direction. A reading sitting in the first zone is an ordinary trend and offers nothing to fade, but a push into the second or third upper zone means price is rising at two or three times the rate required for confirmation, which is statistically unusual and marks the region where an advance is most likely to decelerate and revert toward the band. The trigger for a fade is the turn back down out of the outer zone rather than arrival in it, because a steep slope can hold for a surprisingly long stretch in a genuine trend.
▶ Bearish State (Oscillator Below the Lower Entry Band with Bearish Color)
The normalized slope has cleared the negative entry threshold, confirming that price is declining at a rate meaningful relative to its own volatility. Trend traders use this for short entries or long exits and keep directional bias through corrective bounces that fail to reverse the underlying rate of change. Mean reversion traders again work from zone depth, treating a reading in the lower second or third zone as an accelerated decline that is stretched far enough for a bounce back toward the band to carry a favorable expected move. In either direction, a slope that decays back toward the entry band while price continues in the trend direction is an early rate of change divergence, giving mean reversion traders advance notice of exhaustion and trend traders a reason to tighten stops before the state formally releases.
▶ Neutral State (Oscillator Inside the Threshold Band with Neutral Color)
The oscillator has released into neutral, either because an established regime decayed back through its exit level or because the slope never cleared entry to begin with. This reading carries the same meaning for both styles, since price is neither trending quickly enough to follow nor stretched far enough to fade. Trend traders stand aside and watch for the compression that frequently precedes the next confirmed regime, while mean reversion traders treat the return into the band as a completed reversion and the natural place to close a fade, the move having exhausted itself by definition once the slope no longer clears the threshold.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets tailored to different trading styles and timeframes, each configuring the slope window, normalization length, entry threshold, exit fraction, and normalization method together so the threshold always stays matched to the units it is measured in. "Default" balances noise filtering against responsiveness for swing trading on 4-hour and daily charts. "Fast Response" shortens the window and lowers the entry threshold to engage regimes early for intraday use on 5-minute to 1-hour charts, while a raised exit fraction releases them quickly. "Smooth Trend" lengthens the window and raises the entry threshold to produce few, high conviction regimes held through deep pullbacks, suited to position trading on daily and weekly charts.
▶ Built-in Alerts: Six alert conditions plus a dynamic alert message enable automated monitoring of regime transitions without constant chart observation. "Bullish State" and "Bearish State" trigger on first confirmation of a directional regime, "Neutral State" fires when a directional regime is released, and "Any State Change" provides a combined alert covering all transitions through a single setup. "Bullish Zero Cross" and "Bearish Zero Cross" track the moment the slope changes sign, offering an earlier and more sensitive trigger than threshold confirmation.
▶ Visual Customization: A Candles or Line display toggle switches between the full synthetic slope candle series and a single plotted value for a lighter, cleaner presentation. In Candles mode, an optional Heikin-Ashi transform makes sustained trend phases visually contiguous, and hollow up candles layer bar direction on top of the regime color so momentum inside a state can be read at a glance, for example a filled bar within a bullish phase indicating the slope eased on that bar. Graduated threshold zones fill at one, two, and three multiples of the entry threshold at progressively increasing transparency, giving an immediate sense of how far beyond confirmation the current reading sits.
Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart themes with coordinated bullish and bearish schemes applied consistently across every element.
อินดิเคเตอร์

MovTrend Pullback SystemWhat it is: A trend-following 5 minute indicator built around a linear regression trend line ("MovTrend") with ATR-based volatility bands. It generates four distinct signal types, each answering a different question about price action relative to the trend.
Core components
MovTrend Line (MT) — A linear regression line (ta.linreg) plotted over price, colored by direction: green when sloping up, red when sloping down, gray when flat. This is the trend backbone everything else references.
Slope — The MT line's rate of change over a lookback window, plotted as a histogram in the lower pane. Crossing above/below configurable thresholds marks a "confirmed" up or down trend (green/red bars); values between thresholds are a gray "no-trade zone" where the trend isn't strong enough to trust.
ATR Bands — Upper/lower bands plotted around the MT line at a multiple of ATR, representing a "normal" volatility envelope. Price moving outside these bands is considered stretched/overextended relative to the trend.
The four signals
🟢 Buy Dot / 🔴 Sell Dot (Pullback Touch)
Fires when price dips down and touches the MT line during a confirmed uptrend (buy), or pokes up and touches it during a downtrend (sell), then closes back in the trend's favor. This is the core "buy the dip / sell the rip" signal — a shallow pullback to the trend line that holds.
🟡 Stretch Dot (Mean-Reversion Warning)
Fires when price closes outside the ATR bands — i.e., stretched further from the trend line than normal volatility would suggest. Dot size scales with how extreme the stretch is (tiny = mild, small = moderate, orange/normal = extreme), giving you an at-a-glance read on how overextended price is. This isn't a reversal signal on its own — it's a caution flag that price may be due to snap back toward the MT line. It's filtered by:
Volatility regime — suppressed during low-volatility chop, since a "stretch" in dead conditions is less meaningful
FVG confluence — checks if price is near a fair value gap, adding context to the stretch
Volume — requires above-average volume to confirm real participation, not just a thin drift
Slope deceleration — confirms the trend itself is actually losing momentum, not just that price poked outside the band
🔷 Trend Continuation Diamond (cyan up / magenta down)
Fires on a high-volume push with the trend, away from the MT line — meant to catch strong continuation moves the pullback-touch signal misses (since it only fires on touches, not on strength). It's built specifically to avoid firing at exhaustion tops/bottoms by requiring:
Volume that is not the largest in the recent lookback window (avoids climactic blow-off bars)
Slope that's still accelerating, not flattening
A cooldown between diamonds so one strong leg doesn't spam multiple signals
Filters that apply across signals
Session filter — dims the chart and can gate signals outside your configured trading hours, since overnight/thin-liquidity behavior isn't comparable to regular session action
MTF confirmation — optionally requires a higher timeframe's slope to agree before a buy/sell touch fires, filtering out signals that look right locally but fight the bigger picture
Signal conflict resolution — a Trend Continuation diamond won't fire on the same bar as a Buy/Sell touch, avoiding mixed signals
Performance tracking table
How to read it together
The intended workflow: use the MT line + slope histogram to establish trend context, take Buy/Sell touches as primary pullback entries in the direction of that trend, treat Stretch dots as a caution/take-profit signal rather than a new entry, and use Continuation diamonds as confirmation that a trend still has legs when you're already in a position or considering adding. อินดิเคเตอร์

Gold/Silver Pairs Scalper🟢 Gold/Silver Pairs Scalper
Gold/Silver Pairs Scalper identifies temporary relative-value gaps between Gold and Silver and generates market-neutral pair signals:
LONG GOLD / SHORT SILVER
SHORT GOLD / LONG SILVER
It does not predict the outright direction of precious metals. It trades the relative movement between the two assets.
This is statistical arbitrage, not risk-free arbitrage.
🟢 MODEL
Signals are calculated from fixed reference markets:
Gold — OANDA:XAUUSD
Silver — OANDA:XAGUSD
The model combines:
- Beta-adjusted Gold/Silver return divergence
- Gold/Silver price-ratio deviation
- Rolling correlation validation
- Rolling beta hedge sizing
The calculations follow the active chart timeframe.
The recommended timeframes are 3 minutes and 5 minutes.
🟢 GAP SIGNAL
The return gap measures Silver’s movement relative to its expected movement based on Gold:
Return Residual
= Silver Return − Beta × Gold Return
The model also evaluates the Gold/Silver price ratio.
High Gold/Silver ratio → Adds Short Gold / Long Silver pressure
Low Gold/Silver ratio → Adds Long Gold / Short Silver pressure
Both components are standardized and combined into one pair score.
When an extreme gap begins moving back toward its mean:
Positive extreme → LONG GOLD / SHORT SILVER
Negative extreme → SHORT GOLD / LONG SILVER
New positions are allowed only while the Gold/Silver correlation and beta remain valid.
⚖️ POSITION SIZE
The displayed position size adjusts for both the absolute price difference and rolling beta:
1 GOLD : 24.82 SILVER
This is an ounce-equivalent hedge ratio, not a futures contract ratio.
For futures, contract multipliers must be applied separately:
GC — 100 troy ounces
SI — 5,000 troy ounces
Because futures contracts use fixed sizes, the actual hedge may differ from the theoretical ratio after contract rounding.
🔺 SIGNAL MARKERS
Green upward triangle — Long entry
Red downward triangle — Short entry
Green circle — Long exit
Red circle — Short exit
Gold and Silver are managed as one pair position. Both legs enter and exit from the same pair signal.
For example:
Gold chart → Green upward triangle
Silver chart → Red downward triangle
This represents Long Gold / Short Silver.
⏹ EXIT CONDITIONS
The complete pair is closed when:
- The gap returns to the mean-reversion threshold
- The gap expands another 1.25σ against the position
- Correlation or beta becomes invalid
- The position reaches the 100-bar holding limit
- Leveraged pair loss reaches −100%
📊 STATUS
READY (Waiting for a valid entry)
LONG (Current chart asset is long)
SHORT (Current chart asset is short)
WARMUP (Collecting required historical data)
BLOCKED (Correlation or beta is invalid)
COOLDOWN (Waiting briefly after an exit)
LIQUIDATED (Equity reached −100%; trading halted)
LONG and SHORT always describe the asset displayed on the current chart.
During the same pair trade, the Gold chart and Silver chart therefore display opposite directions.
〽️ OSCILLATOR
The lower oscillator displays the final Gold/Silver pair score.
On a Gold chart:
Above zero → Gold
Below zero → Silver
On a Silver chart:
Above zero → Silver
Below zero → Gold
The oscillator is inverted on the Silver chart so its direction corresponds to the active Silver leg.
🖥️ RECOMMENDED LAYOUT
Use a two-chart layout or two separate windows:
Chart 1 — Gold
Chart 2 — Silver
Both charts should use the same 3-minute or 5-minute timeframe.
If only one chart is used, only that asset’s signals are displayed, so the complete Gold/Silver pair trade cannot be followed.
For a synchronized two-chart layout, use:
Symbol OFF
Interval ON
Crosshair ON
Time ON
Date range ON
Keeping Symbol disabled allows one chart to remain on Gold and the other on Silver. The remaining options keep both charts aligned to the same timeframe and time position.
📈 PERFORMANCE
Cumulative Return includes closed-trade results and the unrealized P&L of the active pair position after applying the selected leverage.
Sharpe is calculated from completed UTC daily mark-to-market equity returns. Trading Period runs from the first entry to the latest calculated bar.
Performance is simulated with no commissions, spread, slippage or financing costs, so actual results may differ.
⚠️ DISCLAIMER
This indicator is provided for informational and educational purposes only and does not constitute financial or investment advice.
Historical and simulated performance does not guarantee future results. High leverage can result in rapid and complete loss of capital. All trading decisions remain the sole responsibility of the user. อินดิเคเตอร์

Key Levels - Cash MarketThis is a Pine v6 modernization of the original SpacemanBTC Key Levels indicator. The original was already a useful way to keep important higher-timeframe levels on chart, but parts of the session logic, timezone handling, and display system were showing their age—especially for equities and index futures traders.
This version keeps the same core idea while rebuilding the underlying logic for cleaner, more reliable behavior.
What changed
Updated to Pine Script v6
Modernized the codebase and removed a large amount of repetitive legacy plotting logic.
Cash-market sessions instead of FX-style sessions
London, New York, and Tokyo now use their actual local cash-market hours rather than generic FX session windows.
Timezone-aware session handling
Sessions use Europe/London, America/New_York, and Asia/Tokyo, so daylight-saving changes are handled automatically.
More reliable session High / Low / Open levels
Session tracking was rebuilt to reset from the actual first bar of each session, avoiding incorrect levels caused by gaps, stale values, or RTH-only charts.
Improved Tokyo handling
The Tokyo range accounts for the exchange's midday lunch break while preserving the morning range into the afternoon session.
Non-repainting Current Year levels
Current Year High, Low, and Mid were rewritten to avoid higher-timeframe lookahead behavior that could make historical levels differ from what was available in real time.
Improved Monday Range for futures
Uses TradingView's trading-day logic so overnight futures sessions—such as NQ beginning Sunday evening—are correctly associated with Monday.
Simplified display controls
The old Distance and Anchor Distance controls were replaced by a single Right Offset setting. Right Anchored mode now simply starts levels at the current bar.
Cleaner session settings UI
Each cash session now has its enable toggle, session time, and color on the same row.
Global Coloring is now truly global
London, New York, and Tokyo session levels now respect the Global Coloring setting as well.
Based on the original Key Levels SpacemanBTC IDWM source. The original source credited @sbtnc for the base code. This version remains open source with credit to the work it was built from.
อินดิเคเตอร์

CRT TCTCRT TCT — Market Structure & Liquidity Toolkit
CRT TCT is a complete price action and market structure indicator designed to help traders identify key liquidity areas, structural shifts, session ranges, and potential liquidity sweeps directly on the chart.
The indicator combines multiple concepts into one clean and customizable trading toolkit, allowing traders to analyze market structure and liquidity without overcrowding their charts.
Key Features
• BOS & CHoCH Detection
Automatically identifies Break of Structure (BOS) and Change of Character (CHoCH) to help visualize bullish and bearish market structure.
• Liquidity Levels
Automatically detects and tracks relevant swing highs and swing lows as potential liquidity areas. Levels remain visible until price trades through them.
• Liquidity Sweeps
Identifies potential bullish and bearish liquidity sweeps where price takes a previous high or low and rejects the level.
• Multi-Timeframe Key Levels
Displays important previous highs and lows from:
H4
Daily
8:00 AM New York H1
9:00 AM New York H1
• Trading Sessions / Kill Zones
Visualizes the main institutional trading sessions:
Asian Session
London Session
New York Session
Session highs and lows can also be extended forward as potential liquidity targets until they are reached.
• Custom Market Structure Timeframe
BOS and CHoCH analysis can use the current chart timeframe or a fixed timeframe such as 5m, 15m, 30m, 1H, 4H, or Daily.
• Market Structure Dashboard
A compact dashboard provides a quick overview of:
Current structural bias
Selected structure timeframe
Active liquidity above price
Active liquidity below price
• Fully Customizable
Traders can independently enable or disable market structure, liquidity, sweeps, higher-timeframe levels, sessions, and other visual elements.
How It Can Be Used
CRT TCT is designed as a confluence and market-reading tool rather than a standalone buy/sell signal system.
It can help traders identify:
Where liquidity may be resting
When liquidity has been swept
Changes in market structure
Continuation through BOS
Important higher-timeframe levels
Session highs and lows
Potential areas of interest during key trading sessions
The indicator can be used across different markets and timeframes depending on the trader's methodology.
Important: This indicator is intended for educational and analytical purposes only. It does not provide financial advice or guarantee profitable trades. Always use proper risk management and combine the information provided by the indicator with your own trading plan and analysis. อินดิเคเตอร์

SmartFit Trend Channels [MarkitTick]💡 This tool builds a linear regression channel that does not sit on a fixed, arbitrary lookback window. Instead, it continuously re-anchors itself at confirmed swing pivots, filters its regression source through a selectable adaptive smoothing stage, validates every channel against a statistical fit-quality test, and optionally gates its breakout signals behind a trend-strength filter. Confirmed breakouts trigger directional alerts (including ready-to-route webhook JSON payloads), while a compact on-chart dashboard keeps the current channel's statistics visible at all times.
✨ Originality and Utility
Most regression-channel tools on the platform work from a single static bar count chosen by the user, redraw the entire channel on every bar, and offer no way to judge whether the underlying price action is actually behaving linearly enough for a straight-line model to be meaningful. This script addresses all three limitations at once. It measures channel validity using the Pearson correlation coefficient rather than assuming a regression fit is automatically useful, it restarts its lookback window dynamically at the most recent statistically valid swing pivot rather than a fixed period, and it finalizes historical segments as discrete drawn objects instead of continuously repainting a single line across the whole chart.
● Why These Components Are Combined
The regression engine, the pivot-anchoring logic, the adaptive source filter, the ADX gate, and the merge engine are not stacked together arbitrarily; each solves a specific weakness left open by the others. The adaptive smoothing stage reduces the high-frequency noise that a raw-price regression is otherwise highly sensitive to. The pivot-anchoring logic solves the "where should this channel actually start" problem that fixed-length regression channels never address. The Pearson fit-quality filter prevents the tool from drawing a confident-looking straight line through what is statistically a sideways, non-linear market. The ADX filter exists specifically to reduce breakout signals firing inside genuinely trendless conditions. The merge engine exists to prevent the chart from filling with redundant, near-identical channel segments once the pivot-anchoring logic starts producing frequent restarts on lower timeframes. Together, these form one coherent statistically-aware channel system rather than five unrelated features bundled for the sake of it.
🔬 Methodology and Concepts
● Regression Engine
At its core, the script performs an ordinary least-squares linear regression across the bars since the current channel's anchor point, producing a slope and intercept that define the channel's midline. This calculation always runs on confirmed, closed price data, never on the live forming bar.
● Statistical Validity Filter
Every regression is scored with the Pearson correlation coefficient, which measures how well price actually fits a straight line on a scale of -1 to 1. A minimum bar count and a minimum absolute correlation strength (both user-configurable) must be met before a channel, or a breakout signal derived from it, is considered valid. Channels that fail this test are still drawn, but are visually flagged as low-confidence rather than treated as a directional signal.
● Deviation Bands
Upper and lower channel boundaries are placed a user-defined number of standard deviations away from the regression midline, based on the vertical dispersion of price around that line. This produces a statistically scaled envelope rather than a fixed-percentage or fixed-tick band.
● Adaptive Source Filter
Instead of regressing on raw closing price, the script can first pass price through one of several smoothing methods, selectable per chart:
SMA / EMA / RMA — standard simple, exponential, and Wilder-smoothed moving averages, offered as baseline options with different responsiveness-to-noise tradeoffs.
Double WMA — a weighted moving average smoothed a second time through another weighted pass, trading additional lag for a cleaner underlying line.
Triple VWMA — a volume-weighted moving average smoothed through three successive passes, intended for instruments where volume-weighting the trend estimate is meaningful.
HMA — a low-lag moving average designed to track price more closely than a standard average of the same length.
LLAMA — a proprietary MarkitTick method that blends a simple average baseline with a linear slope term measured across the filter length, effectively projecting the recent directional momentum forward onto the smoothing output rather than only averaging past values.
Kalman Filter — a recursive single-state estimator that continuously balances its own prediction against each new price print, with the filter length controlling how much weight is given to new information versus the existing estimate.
Selecting "None" regresses directly on the previous confirmed close.
● Dynamic Pivot Anchoring
The script tracks confirmed swing highs and swing lows using a symmetric bar-confirmation window (either auto-scaled to the chart's timeframe or manually set). These pivots are only accepted once enough bars have closed on both sides of the candidate bar to confirm it, so no pivot is ever assumed before it is actually confirmable. When a breakout occurs, the script evaluates whether the most recent opposite-type pivot has a strong enough regression fit of its own to serve as a more representative channel origin; if it does, the newly drawn segment is anchored there instead of at the current bar.
● Confirmation Lag Notice
Because segment anchors are only finalized once a breakout confirms them, a newly drawn historical segment's starting point is placed at a bar in the past, after the fact. This is standard behavior for any pivot-anchored channel tool and does not involve unconfirmed or future data, but it does mean the visual origin of a finalized segment was not known in real time at that bar; it becomes fixed only once the breakout that closes out the prior segment occurs.
● Channel Merge Logic
When enabled, a newly forming channel is compared against the band edges of the segment it is replacing. If the gap between them falls within a user-selected tolerance (expressed as a multiple of the current standard deviation), no new discrete segment is drawn and the channel is treated as a continuation. This keeps visually similar, closely-spaced channels from cluttering the chart as separate labeled objects.
● ADX Trend Filter
An optional Average Directional Index filter can require a minimum trend strength reading before a breakout is allowed to register as a directional signal, reducing the number of signals generated while the market is directionless.
● Breakout Signal Logic and Webhook Alerts
A directional signal fires only on a confirmed bar, only when the minimum bar count and fit-quality thresholds are met, and only once per new breakout (not on every bar the price remains beyond the band). Each signal type — long entry, short entry, and their corresponding opposite-side close — has its own configurable action label, which is packaged into a JSON payload suitable for forwarding to third-party automation or webhook services.
🎨 Visual Guide
The live, currently forming channel is drawn as three connected lines — an upper band, a midline, and a lower band — with the space between the bands filled in a translucent color. Green indicates a bullish-sloped channel, red indicates a bearish-sloped channel, and gray indicates a channel that has not met the minimum fit-quality threshold and should be treated as statistically unreliable. A small label at the live edge of the channel states its bias, its fit percentage (the Pearson correlation expressed as a percentage), and its standard deviation value. When a segment finalizes, its own colored line-and-fill combination plus a labeled marker remain on the chart as a permanent historical record of that channel. An optional setting recolors the chart's candles using the live channel's bias color for an at-a-glance read of current conditions without needing to look at the channel itself. In the corner of the chart (position configurable), a compact dashboard table lists the ticker and timeframe, current bias, a bar-style fit-quality gauge, the standard deviation value, the current upper and lower band prices, the number of bars in the active channel, the pivot length in use, the current breakout/breakdown state, and — only when the relevant filters are enabled — the live ADX reading and the selected adaptive filter type.
📖 How to Use
Read channel color and the dashboard's Bias row together: a green, high-fit-percentage channel reflects a statistically supported uptrend in the regression sense, while red reflects the equivalent downtrend condition. Treat gray, low-fit-percentage channels as periods where price is not moving in a way a straight line meaningfully describes, and weight any signal generated during those conditions accordingly. A directional signal, visible as a Breakout or Breakdown state on the dashboard and paired with an alert firing, indicates confirmed price has closed beyond the channel's statistical deviation band with sufficient trend history and fit quality behind it — this is a signal generator, not a backtested strategy, so no historical win-rate or equity curve is produced by the script itself. Enabling the ADX filter is most useful on instruments or timeframes prone to frequent whipsaw, where it will suppress breakouts that occur without adequate underlying trend strength. Choosing a smoother adaptive filter (Double WMA, Triple VWMA) will produce fewer but later channel restarts; choosing a more responsive one (HMA, Kalman, LLAMA) will track price more closely at the cost of more frequent re-anchoring. Enable channel merging on lower timeframes or choppier symbols to keep the chart readable; disable it if you want to see every discrete regression segment the script produces. To receive the webhook-ready alerts, create an alert on the script using the "Any alert() function call" option, or select one of the four named alert conditions individually if only a subset of signals is needed.
⚙️ Inputs and Settings
The Core group controls the statistical backbone of the tool: automatic or manual pivot lookback length, whether nearby channels merge and how strict that merge tolerance is, the minimum Pearson fit strength and minimum bar count required for a channel to be considered valid, and the deviation z-score used to size the bands. The Filters group holds the optional ADX trend gate (toggle, threshold, and length) and the adaptive source filter selection along with its length. The Visuals group controls channel line width and whether chart candles are recolored by the live channel bias. The Dashboard group sets which corner of the chart the statistics table is drawn in. The Alerts group defines the text sent in the "action" field of each of the four webhook JSON payloads (long, short, close-long, close-short), allowing the payload vocabulary to be matched to whatever automation platform is receiving it. The Colors group governs the bullish, bearish, and weak-fit channel colors, the support/resistance accent colors used in the dashboard gauge, and the dashboard's background, header, text, and warning colors.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
The regression core is an ordinary least-squares fit — the same slope and intercept formulas taught in introductory statistics, chosen because they minimize the sum of squared vertical distances between the line and each price point in the window. Layered on top of this is the Pearson product-moment correlation coefficient, the standard statistical measure of how strongly two variables are linearly related; applying it to price-versus-time is the same logic underlying R²-based confidence filters used in quantitative trend-following research, here repurposed as a simple accept/reject gate for whether a channel is worth trusting. The deviation bands draw on the same statistical foundation as Bollinger-style envelopes — a mean or trend estimate flanked by a multiple of the underlying standard deviation — except the dispersion here is measured as residual distance from a sloped regression line rather than from a flat moving average, and a z-score of 1.96 specifically corresponds to the approximate 95% interval of a normal distribution, a deliberate nod to standard statistical confidence-interval convention. The pivot-confirmation logic is a symmetric-window fractal test in the tradition of classic swing-high/swing-low detection methods, used here purely as a principled way to choose a channel's starting point rather than as a standalone trading signal. The ADX/DMI component follows Welles Wilder's original directional movement framework for measuring trend strength independent of trend direction. Among the adaptive filters, the Kalman option applies a simplified single-state predict-correct estimator common in signal processing and control theory, while the LLAMA option applies a linear-extrapolation-style adjustment to a moving average — conceptually related to trend-adjusted smoothing methods such as Holt's linear exponential smoothing, which projects recent momentum forward rather than only averaging past observations.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. We expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. อินดิเคเตอร์

Market Rotor - Rotation Artifact Null Test [FibonacciFlux]Market Rotor is the first of a series of published experiments: take a correction that is widely assumed to work, implement it honestly, and find out what it actually does. This one tests the standard artifact correction for cross-sectional rotation - the claim that you can estimate each asset's own autocorrelation, subtract the rotation that autocorrelation implies, and treat whatever is left as genuine lead-lag.
Implemented and measured, it does not do that. The script is published so the test can be repeated and the result attacked.
🔶 USAGE
🔹 What this is for
Before you build on, or believe, a rotation or lead-lag indicator, load your basket here. If an artifact component is identified, an artifact component is present in the rotation this basket produces at this window - which is reason to check whether the indicator you were about to trust is reading the same thing. If nothing is resolved, you have learned that this particular correction cannot tell you either way - which is worth knowing, because the correction is usually assumed to work rather than checked.
🔹 Reading the shading
The background has two states and neither of them is an all-clear:
Amber - R-squared above zero. An artifact component was identified inside the rotation you are looking at.
Grey - R-squared at or below zero. Nothing was resolved. This is not evidence that the rotation is genuine.
Two months of BINANCE:BTCUSDT 1H at the defaults. The two states alternate throughout - there is no long stretch where the correction cleanly resolves anything.
There is deliberately no green state anywhere in this script. A reassuring colour would be the most misleading thing it could draw, because the test is structurally incapable of certifying that an observed rotation is real.
🔹 Reading the plots
Three Frobenius norms share the pane. Grey is the observed rotation, the amber filled area is the artifact estimate, green is the residual. These are matrix norms, not components: they do not sum, and the residual can and often does exceed the observed norm. When it does, subtracting the artifact estimate has added variance rather than removed it - see the noise floor below.
The Data Window carries the quantities that actually matter: R-squared, the residual share, the direction agreement cos(Ω, Ω_art), the mean off-diagonal of G0, the four estimated AR(1) coefficients, the effective sample count, and the legacy statistic from the first version of this script, kept only for comparison.
🔹 Choosing the symbol set
The artifact term is proportional to contemporaneous co-movement. If your four assets barely co-move, or their bars do not align - mixing a stock with 24/7 crypto is the common case - the artifact estimate collapses toward zero for reasons that have nothing to do with lead-lag, and the test silently becomes vacuous. Watch the mean off-diagonal of G0 in the Data Window: if it is small, the reading means nothing.
The same script on NASDAQ:AAPL daily with the three Binance defaults left in place - the first thing most readers will try. Nothing warns you. On the bar shown, the mean off-diagonal of G0 falls from 0.87 to 0.34, the artifact estimate collapses with it to 0.016 against an observed norm of 0.081, cos(Ω, Ω_art) reads -0.85, and the residual ends up larger than the observed rotation it came from. Note what the old v1 statistic does here: 0.20, which under that version's bands was its most reassuring possible reading. The tool's least trustworthy configuration was the one it praised.
Requests use gaps_on, so a symbol with a missing bar yields na and that bar is skipped rather than having a stale return carried into the estimate.
🔹 Warm-up and repainting
Nothing plots until the window is full and W + z-score-length bars have elapsed: 500 bars at the defaults, roughly three weeks of 1H data, but around two years on a daily chart. If the pane is empty, that is why. The accumulator only advances on confirmed bars, so historical values do not repaint.
🔶 DETAILS
🔹 The identity being tested
Let each asset follow its own AR(1) with coefficient phi_i, and let the true cross-asset lead/lag be identically zero:
r = phi_i * r + e
G1 = E [ r * r ] = phi_j * G0
G0 is symmetric, therefore
Om = 0.5 * (phi_j - phi_i) * G0
Exact in population. The proposal it suggests - estimate phi from each asset's own autocorrelation, form the implied artifact, subtract it, call the remainder genuine lead-lag - is what this script implements so that it can be tested rather than assumed.
🔹 Where the numbers come from
The core was reimplemented outside Pine and agrees with this script to five decimal places on the same bar; every figure below comes from that reimplementation. Figures labelled synthetic are generated with a seeded generator and known ground truth, so they reproduce exactly. Real-data figures name the symbol, timeframe and window they were taken on, and the two single-bar readings are marked as such.
🔹 Result 1: the correction is not identified
phi_i estimated from asset i's own autocorrelation cannot distinguish "asset i is autocorrelated" from "asset i is led by asset j", because the second necessarily produces the first. On synthetic data where a genuine lead-lag is injected, the artifact model fits better , not worse: R-squared rises to +0.40 and cos(Ω, Ω_art) to +0.74 at W=250. The correction absorbs precisely the thing it is meant to leave behind.
🔹 Result 2: the subtraction is noise-dominated
Ω is estimated from the off-diagonal of G1; the artifact term from the diagonal of G1 plus G0. Under the null these estimate the same population quantity. If their errors are of comparable size and not strongly correlated, Var(Ω_res) = Var(Ω) + Var(Ω_art) and the residual share tends to sqrt(2) = 1.414 when noise dominates. Both of those are assumptions rather than results - the two estimators are built from the same return pairs over the same window, and the null identity ties them together - so read the measured spread as the test of them, not as a confirmation of the algebra. On synthetic all-artifact data it lands between 1.10 and 1.88, straddling that value, and the finding that survives either way is that the residual is larger than the quantity it was subtracted from. On BINANCE:BTCUSDT 1H with the default basket at W=250, the median R-squared is about -0.7 - near the noise floor of -1.
🔹 What the first version of this script got wrong
Version 1 shaded on ‖Ω_art‖ / ‖Ω‖. That statistic compares magnitudes only and is not a fraction-explained, because the artifact and residual matrices are not orthogonal. It read 0.96 - "almost entirely artifact" - on data whose true explained share was 0.41, while the residual line sat at 77% of the observed line directly beside it. It also produced its most reassuring readings on baskets that barely co-move. Both statistics are exposed in the Data Window now - R-squared and the v1 ratio side by side - so the discrepancy can be inspected rather than taken on trust.
🔹 Implementation and reproducibility
N is fixed at four because the external series are requested at global scope. G0 and G1 are uncentred second moments, not covariances; centring them inside the window was tested and moved R-squared by less than 0.02, so the extra accumulators are not carried. Rolling sums of the sixteen products are maintained by hand in a circular buffer, because built-in series functions keep per-call-site state and return wrong values inside loops. The core was independently reimplemented outside Pine and agrees with this script to five decimal places on the same bar; the synthetic scenarios use a seeded generator so the numbers above are reproducible.
🔶 SETTINGS
🔹 Symbols
Symbol 2, Symbol 3, Symbol 4 - the three series joined to the chart symbol, which is always the first. Defaults are ETHUSDT, SOLUSDT and XRPUSDT on Binance.
🔹 Windows
Rolling window W - length of the moment window, default 250, minimum 100, maximum 1000. Below about 100 the estimates are pure noise and the shading strobes, which is why the minimum is not lower.
Return z-score length - lookback used to standardise each return series, default 250.
🔹 Display
Show ‖Ω‖, ‖Ω_art‖, ‖Ω_res‖ - the three norms.
Shade background when an artifact component is identified - the amber/grey band.
Show residual signal for the chart symbol - off by default, and drawn for inspection only. It is signed and lives on a different scale to the three norms. Result 2 above is the reason not to trade it: this residual is noise-dominated and routinely larger than the observed norm it came from.
Signal display scale - default 0.2. Raising it flattens everything else in the pane.
Open source under the Mozilla Public License 2.0. Replications and refutations are welcome, particularly from anyone who can construct an estimator of the artifact term that stays identified when a genuine lead-lag is present.
อินดิเคเตอร์

Market Rotor - Increment Contamination Test [FibonacciFlux]Second in a series of published experiments: take a correction that is widely assumed to work, implement it honestly, and find out what it actually does. This one tests the most common way of accidentally manufacturing rotation - putting the same-bar price increment into the second axis and then reading the resulting circulation as structure.
It detects that contamination reliably, though not precisely - the spread is measured below. It cannot do the converse, and the boundary where it starts getting the converse wrong is measured below.
🔶 USAGE
🔹 What this is for
Any indicator that claims rotation, circulation or lead-lag between price and a flow-like series is reading the antisymmetric part of a lag-1 covariance. Load your two axes here first. If the reading comes back near 1, the circulation that indicator is showing you is the increment leaking into its own second axis, and there is nothing else to interpret.
🔹 Reading the shading
Red - the ratio sits within 0.25 of 1. An increment-contamination component accounts for the observed circulation.
Grey - anything else. Not classified. This is not evidence that the rotation is genuine.
BTCUSDT 1H at the defaults. The band is red across effectively the whole span, and that is the finding rather than a rendering quirk: on this data the circulation between price and flow is contamination-shaped nearly all of the time. Note also how much of the pane the amber R_art area occupies relative to the pale R_obs line running through it - the artifact term is routinely larger in magnitude than the thing it is decomposing, which is why the ratio sits above 1 in about two thirds of readings.
There is no green state, for the same reason as in the first script: this test is one-directional. It can find contamination; it cannot certify its absence.
🔹 Reading the plots
The amber filled area is R_art, the circulation Identity I alone accounts for; the pale line inside it is R_obs, the observed circulation; green is R_res, what is left. The verdict band is red rather than amber precisely so that it is not the same colour as the series it is a verdict about.
The ratio is a signed share, not a fraction. R_res is defined as R_obs - R_art, so the additive identity cannot fail and proves nothing by itself; what justifies the split is that LAMBDA is linear in y, so writing y = beta*dx + e gives R_art and R_res exactly as the circulation contributed by each part. Nothing bounds the ratio to , and on real data it usually is not there: on BTCUSDT 1H it exceeds 1 in 66% of readings on the default axis, 79% on the order-flow axis. Read "near 1" as "contamination accounts for it", never as a percentage of it.
The Data Window carries the ratio, beta, corr(y, dx), LAMBDA, T_K and both axes.
🔹 Choosing the second axis
CLV x volume is the default, and deliberately not the best proxy. Order flow from lower-timeframe volume delta is the better second axis. The original reason for not defaulting to it was that a chart tab hung twice while it was selected, once on a daily chart and once on the 1H default, both on a two-core machine.
That attribution has since weakened and this paragraph is the correction. Both of those tabs stopped responding during automated testing, not during ordinary use. The same symptom later appeared twice more with no lower-timeframe request involved at all, and the axis has since been selected and exercised on a 1H chart without incident. Nothing here is attributable to the request. The default stays on CLV as the conservative choice rather than as a fix for a diagnosed problem - select order flow deliberately, not nervously.
What the default does buy you is real, and it is a cost rather than a hazard: request.* must sit at global scope, so the call always runs, but the timeframe it asks for is now conditional. On any axis other than order flow it is pointed at the chart's own timeframe and returns one intrabar per bar instead of sixty.
Volume z-score on its own is the useful control: it carries almost no increment at all (beta +0.016, corr +0.009), and its ratio consequently degenerates - a non-verdict, not a clean bill of health. Momentum is a control, not a choice - it sets y to a difference of return EMAs, which is nearly dx itself. Watch beta when you switch to it, not the ratio: measured on one bar of BTCUSDT 1H the ratio barely moved (1.119 to 1.084) because the default is already saturated near 1, while beta on that same bar jumped from 0.838 to 1.270. The identity is firing; the ratio has no room left to show it.
The four axes disagree, and that is information rather than a defect. On one bar of BTCUSDT 1H: order flow 1.119, CLV x volume 0.965, momentum 1.084 - and volume z-score -2.104, which is not a verdict at all but the signature of a near-zero denominator, discussed below.
🔹 Warm-up and repainting
Nothing plots until 2 x W + z-length + detrend-length bars have elapsed: 574 at the defaults, about 24 days of 1H data.
Two things that will bite you. First, when R_obs is near zero the ratio is meaningless and still prints to five decimals - on the volume z-score axis this was measured at R_obs 0.013 giving a ratio of -2.10 with beta 0.07, that is, no contamination at all and a nonsense ratio. Read LAMBDA first: if there is no circulation, decomposing it means nothing. Second, if you switch to the order-flow axis, set the lower timeframe explicitly before going above 4H - on a daily chart the warm-up needs roughly 14,000 intrabars.
And one silent substitution. Where the lower-timeframe request returns nothing - beyond the intrabar history limit, or on a plan that cannot serve the chosen lower timeframe - y falls back to CLV with no visible break. The plotted history can therefore be a mixture of two different second axes with an invisible switchover, and every Data Window statistic inherits it. Watch corr(y, dx) and beta for a step change if that matters to you.
🔶 DETAILS
🔹 The identity being tested
R_obs = 2 * LAMBDA, LAMBDA = 0.5 * mean_W
if y carries the same-bar increment dx with coefficient beta then
Q(w) = -beta * S_xx(w) * sin(w) appears with no rotation present at all
beta = cov_W(dx, y) / var_W(dx)
R_art = 2 * beta * 0.5 * mean_W
In discrete time x_s(y_{s+1}-y_s) - y_s(x_{s+1}-x_s) collapses exactly to x_s*y_{s+1} - y_s*x_{s+1}, so the circulation needs no angles, no atan2, no origin estimate and no lag operator. An earlier version of this work used atan2 and every one of those was required - each a free parameter able to manufacture the result.
Call it circulation, not a rotation rate: mean is mean , an areal velocity, and it equals a rotation rate only if the squared radius and the angular velocity are uncorrelated.
🔹 What it detects, and what it does not
Reimplemented outside Pine and swept over synthetic series whose truth is known by construction, 5 seeds, W = 250:
y = beta*dx + noise, no rotation at all - the ratio has median 0.94 to 0.97 with a 10th-to-90th percentile spread of roughly 0.77 to 1.17. Centred on 1, but not precise, and independent of the sign of beta.
a clean 2-D rotation with no dx in y at all - the ratio reads 0.46 to 0.83, rising with rotation speed. The test therefore cannot certify that a rotation is genuine.
The false positive depends on persistence at least as much as on speed. The rotation speed at which a clean, uncontaminated rotation starts reading above 0.75 and is reported as contamination, by the AR persistence rho of the rotating system:
rho 0.90 never, up to 1.5 rad/bar
rho 0.95 0.50 - 0.70 rad/bar (~9-13 bar cycle)
rho 0.98 0.25 - 0.40 rad/bar (~16-25 bar cycle)
rho 0.995 0.12 - 0.16 rad/bar (~39-52 bar cycle)
W and the noise level did not move that boundary; persistence moved it by more than 5x.
The sign of beta is deliberately not used for anything. Across more than 50 configurations it tracks the sign of whatever coupling exists, flipping with the direction of a genuine rotation as readily as with the sign of the contamination. Related structural fact, worth checking rather than trusting: LXD is non-positive by construction, so the sign of R_art is fixed by the sign of beta. Measured across synthetic rotation in both directions, synthetic contamination and real data, LXD was positive in 0.0% of readings.
🔹 On real data
Two structurally different flow proxies give the same verdict on 1H crypto, which is the finding worth taking away:
ratio beta corr(y,dx)
CLV x volume BTCUSDT 1.082 +0.49 +0.30
ETHUSDT 1.085 +0.58 +0.36
taker flow BTCUSDT 1.090 +0.79 +0.47
ETHUSDT 1.052 +0.65 +0.39
volume z BTCUSDT 0.664 +0.016 +0.009 <- the control
My own earlier work on this data, which this script reimplements, reported 108.3% with corr +0.377 on its own flow proxy, and the live script on lower-timeframe volume delta reads 1.119 with corr +0.533. Four different constructions of the second axis, one answer: the circulation people read between price and flow is the increment leaking into the flow axis.
🔹 Implementation and reproducibility
Covariances are computed from their definition because Pine has no ta.cov. y is never lagged: an earlier cycle established that lagging it manufactures rotation and reverses the sign of the true antisymmetric lag covariance. The x pipeline was verified against an independent reimplementation - identical to five decimal places on the same bar. The synthetic scenarios use a seeded generator, so every number above is reproducible.
🔶 SETTINGS
🔹 Axes
Second axis y - CLV x volume (default), order flow from lower-timeframe volume delta, volume z, or the momentum control.
Equilibrium EMA - detrends x (default 34).
Z-score length - standardises both axes (default 40).
Lower timeframe for volume delta - blank picks one from the chart timeframe.
🔹 Windows
Rolling window W - LAMBDA, beta and T_K are all estimated over it (default 250, minimum 100; shorter windows make the verdict band fragment into bar-to-bar stripes).
Warm-up multiplier - bars withheld before plotting, as a multiple of W (default 2).
🔹 Display
R_obs, R_art, R_res - the three series.
T_K residual torque - off by default; a volume-weighted detailed-balance statistic that did not survive its own null.
Shade background when contamination is identified - the red band.
T_K display scale - default 30, because T_K is far smaller than the three circulation series and draws as a flat line on zero at 1; 30 is simply what made it readable here.
Open source under the Mozilla Public License 2.0. Replications and refutations welcome, particularly a second-axis construction that stays uncontaminated under a test I have not thought of.
อินดิเคเตอร์

Volatility Epicenter and AftershocksVolatility Epicenter and Aftershocks is an event-conditioned market-memory indicator. It detects moments when a recent six-bar path is unusually dominated by one or two returns and unusually active relative to the same part of the trading session.
When a primary Shock is confirmed, the indicator freezes a movement box around that bar's close. The box does not say price will rise or fall. Its height comes from the maximum excursions of completed historical Shock events over the same forward horizon.
HOW MARKET MEMORY WORKS
This script does not use an LSTM or neural network. Its memory consists of rolling empirical distributions and a transparent event-state machine.
For log return r(t) = ln(Close(t) / Close(t−1)), the recent path and volatility concentration are:
Path = Σ|r|
Concentration = Σr⁴ / (Σr²)²
Seasonal memory compares the current Path with its median at the same time in previous sessions:
Seasonal Ratio = Current Path / Same-Time Historical Median
A Shock occurs when both Concentration and Seasonal Ratio exceed their rolling percentile thresholds. Thresholds are calculated before adding the current observation, preventing leakage.
After each Shock matures, the script stores its maximum 3-, 5- and 10-bar excursion:
Excursion(h) = max
The box uses the selected percentile of completed 10-bar excursions:
Upper = Shock Close × exp(Excursion Percentile)
Lower = Shock Close × exp(−Excursion Percentile)
The first Shock fixes the box and expiry. Additional detections inside that window become A, B, C aftershocks without restarting it.
In simplified form:
shock = concentration >= historical_threshold
and seasonal_ratio >= historical_threshold
box_height = percentile(completed_shock_excursions)
This is empirical market memory —not ATR, candle-size projection or black-box prediction.
Why this is not another breakout or large-candle script
• A breakout is defined by price crossing a level. Epicenter does not use support, resistance, channels, or prior highs and lows to define a Shock.
• A large-candle alert is usually defined by one candle's body or range. Epicenter evaluates the structure of a multi-bar return path.
• ATR measures average true range. Epicenter asks whether the same amount of movement arrived in a concentrated burst rather than being distributed across bars.
• The empirical box is not an ATR multiple and is not projected from the Shock candle's size. It is learned from completed post-Shock excursions.
What market memory means
Read the chart in ten seconds
• Shock - the primary volatility event. It starts the original movement window.
• Solid rectangle - the empirical range associated with the primary shock.
• A, B, C... - additional shocks detected before the original window ends.
• Dotted rectangles - aftershock context. They are not scored as separate targets.
• Standalone green check - price reached either boundary of the primary box before expiry.
• Standalone red cross - the original window ended before either boundary was reached.
What the box means
The range is learned from the maximum excursions of completed historical shock events. Box-height percentile controls how wide that range is:
• P50 is the typical reach. Approximately half of comparable completed shocks moved farther and half moved less.
• P85 is a wider stress envelope. Only a smaller minority of comparable completed shocks moved farther.
The box is symmetric because the model estimates movement magnitude, not direction. A wider box is not a stronger bullish or bearish opinion.
Practical use
• Separate an ordinary large candle from a path whose volatility structure is genuinely unusual for that session time.
• Add event context to a breakout: a breakout with no Shock is a level event; a breakout with a Shock also carries concentrated-volatility risk.
• Recognize a Shock inside a range even when no breakout system would react.
• Use P50 as a typical remembered excursion and P85 as a wider stress envelope when planning exposure, stops, or monitoring intensity.
• Audit whether the remembered boundary was reached before the original ten-bar window cooled.
How the event is detected
The engine uses confirmed chart bars and combines two conditions across the recent six-bar path:
1. Variance concentration: whether one or two returns dominate the recent path's realized variance.
2. Seasonal volatility abnormality: how active the recent path is compared with the same bar position in prior sessions.
A primary event appears only when both measures exceed their rolling thresholds. Additional detections inside the primary window are labelled as aftershocks rather than restarting the main outcome test.
Non-repainting design
• Events are confirmed only after a chart bar closes.
• The primary box coordinates are frozen when created.
• Aftershocks do not extend or reset the primary box's original window.
• A check or X is added only after the corresponding outcome is observable.
• Keep all preserves historical boxes for audit. Latest only is an explicit display choice that suppresses secondary boxes.
Recommended starting setup
• Timeframe: 15 minutes.
• Session preset: Auto.
• Box-height percentile: 50.
• Box history: Keep all.
• Zone annotations: Marks only.
Recommended presets:
SPY, QQQ and US stocks: US ETF RTH
NQ and ES: CME equity futures
Gold, Silver and energy futures: Metals / energy futures
Bitcoin and crypto: Crypto 24/7
NIFTY and BANKNIFTY: Custom session, 09:15 start and 25 bars per session on a 15-minute chart
BOX HEIGHT
P50 shows the typical historical reach and is the recommended default.
P60 to P75 shows an expanded movement range.
P80 to P85 shows a wider stress envelope.
A higher percentile is not a stronger prediction. It simply displays a wider historical range.
HIGHER-TIMEFRAME BOXES
Use Adaptive mode on charts above 15 minutes. Boxes become available after five completed Shock outcomes and may use outcomes that cross session boundaries.
Strict mode requires the full historical sample and same-session outcomes.
Early Shocks may appear without boxes while the market memory is warming up. The script does not add boxes retrospectively because that would introduce lookahead.
DISPLAY
Keep all preserves historical boxes for auditing.
Latest only keeps the newest primary box.
Marks only is recommended. It displays checks and crosses without adding text inside boxes.
Full text adds explanations inside boxes but may become crowded.
SENSITIVITY
Recommended balanced settings are a six-bar path, concentration percentile of 80, seasonal-volatility percentile of 50 and a ten-bar aftershock window.
Higher thresholds produce fewer and more exceptional Shocks. Lower thresholds produce more signals.
Changing the timeframe, session preset or detection settings recalculates the model across the available chart history. This is recalculation under a different configuration, not repainting.
Session presets are included for US ETF regular hours, CME equity futures, metals and energy futures, crypto, and custom sessions. The model must collect enough calibration and completed-event history before boxes can be displayed.
ALERTS
• Primary volatility epicenter detected.
• Secondary aftershock detected.
• Projected percentile boundary achieved.
• Original aftershock window cooled.
Important limitations
• This is not a buy/sell system and does not predict direction.
• The empirical range describes this symbol's observed history; it is not a guarantee of อินดิเคเตอร์

ATK / DEF MTF Analysis Chameleon Combo SessionATK / DEF MTF Analysis Chameleon Combo Session is a multi-timeframe market observation and visualization tool designed to examine the broader market environment through several independent analytical dimensions.
Unlike traditional single-indicator analysis, this framework combines **MTF Process, MTF Radar, Test Depth Matrix, MTF Direction, and an independent Chameleon MA** into one structured dashboard.
### Core Components
**MTF Process**
Observes changes in higher-timeframe ADX and RSI conditions and classifies the current market process into different states, from accelerating conditions to sideways or declining conditions.
**MTF Radar**
Combines ADX, RSI, and relative ATR to describe the current level of market activity and volatility.
**Test Depth Matrix**
Divides the selected MTF price range into five relative zones:
* Deep Water
* Mid Water
* Shallow Water
* Shallows
* Dry Zone
This provides a visual representation of where the observed market environment is positioned within its selected range.
**MTF Direction**
Uses EMA structure together with DI+ / DI− relationships to classify the directional condition of the selected timeframe.
**Chameleon MA**
The Chameleon component is independently configured and is **not tied to the MTF timeframe setting**. Its moving-average line changes visual state according to its position within the Test Depth Matrix, creating a dynamic zone-based visual layer.
**MTF Final Result**
Combines the independent MTF Process, Radar, Test Depth, and Direction classifications into a normalized composite score for observing the overall market state.
### Multi-Level Market Observation
The framework separates the market into different analytical levels rather than relying on a single indicator reading.
It allows the user to observe:
**Direction → Process → Activity → Depth → Chameleon State → Composite Market State**
The purpose is to provide a broader contextual view of market conditions and how different analytical dimensions interact with each other.
### User Configuration
The indicator is intentionally configurable.
Users must define their own:
* MTF Timeframe
* Chameleon MA Period
* Test Depth Zone Period
* Display settings
The Chameleon parameters are independent from the MTF configuration, allowing the two analytical layers to be adjusted separately.
Different parameter settings can produce different market classifications, so there is no single configuration intended for all symbols or market conditions.
### Important
This indicator is designed **only for market observation, analysis, and visualization**.
It does not provide tadn recommendations, ent or eit instructions, fiial advice, or forts.
The displayed scores and classifications are mathtical representations based on market data and use-selected parameters.
The indicator does not determine what action should be taken.
Use are responsible for selecting and configuring the relevant parameters for their own analysis.
อินดิเคเตอร์

DNSE VN301!, Bollinger Bands Break Out Strategy "Bollinger Bands Breakout with SMA Trend Filter" is a volatility breakout strategy designed to capture strong directional price movements when price breaks outside its recent trading range. The strategy uses Bollinger Bands, constructed from an SMA(20) and two standard deviations, to identify bullish breakouts when price closes above the upper band and bearish breakouts when price closes below the lower band.
To improve signal quality, the strategy incorporates an optional SMA(200) trend filter, allowing Long trades only when the SMA is rising and Short trades only when it is falling. By combining volatility-based breakout signals with long-term trend confirmation, the strategy seeks to reduce false breakouts during ranging markets while participating in sustained intraday trends. It also includes configurable stop loss, take profit, trading session filters, automatic end-of-day position closure, and trend reversal exits for disciplined risk management.
Strategy settings and configuration:
Chart timeframe: recommended 5-minute chart
Position size: 3 contracts
Bollinger Bands length: 20
Bollinger Bands multiplier: 2.0
SMA length: 200
Stop loss: 10 points
Take profit: disabled
SMA trend filter: On / Off
Take profit: On / Off
Time filter: On / Off
Trading session: 09:00 – 14:30
Trade direction: Long / Short / Both
Default script settings:
The strategy calculates Bollinger Bands using the SMA(20) of the closing price. The upper and lower bands are created by adding or subtracting two standard deviations around the middle line.
When volatility increases, the Bollinger Bands expand. When the market is quiet or moving sideways, the bands contract.
When the closing price breaks above the upper Bollinger Band, buying pressure may be taking control. When the closing price breaks below the lower Bollinger Band, selling pressure may be taking control.
When the SMA(200) trend filter is enabled, the script only allows Long trades when SMA(200) is rising and only allows Short trades when SMA(200) is falling. When the SMA filter is disabled, the strategy can trade both directions based only on Bollinger Bands breakout signals.
Users can add the built-in Bollinger Bands indicator on TradingView with Length 20 and Multiplier 2.0 to visually monitor the signal on the price chart.
Entry and exit rules:
Long entry:
Closing price > upper Bollinger Band
AND SMA(200) is rising, if the SMA filter is enabled
AND the signal appears during the trading session
AND trade direction allows Long entries
Long exit:
Stop loss: 10 points from entry price
Take profit: disabled by default
Closing price touches or breaks below the lower Bollinger Band
SMA(200) turns downward, if the SMA filter is enabled
Reversal when a valid Short signal appears
Automatic position close at the end of the trading session
Short entry:
Closing price < lower Bollinger Band
AND SMA(200) is falling, if the SMA filter is enabled
AND the signal appears during the trading session
AND trade direction allows Short entries
Short exit:
Stop loss: 10 points from entry price
Take profit: disabled by default
Closing price touches or breaks above the upper Bollinger Band
SMA(200) turns upward, if the SMA filter is enabled
Reversal when a valid Long signal appears
Automatic position close at the end of the trading session
Risk disclaimer:
Futures trading involves a high level of risk and prices can move sharply. This script is provided for reference, research, and backtesting purposes only. Users should fully understand derivatives trading, their own risk tolerance, and the strategy logic before applying it to live trading.
All investment decisions are the responsibility of the user. phaisinh.online is not responsible for any losses arising from the use of this strategy in real trading. Past performance does not guarantee future results.
____________________________________________________________________
"Bollinger Bands Breakout với Bộ lọc Xu hướng SMA" là một chiến lược giao dịch theo xu hướng dựa trên sự bứt phá của biến động giá, được thiết kế nhằm nắm bắt các chuyển động mạnh theo một hướng khi giá vượt ra khỏi vùng dao động gần nhất. Chiến lược sử dụng Bollinger Bands, được xây dựng từ SMA(20) và 2 độ lệch chuẩn, để xác định tín hiệu mua khi giá đóng cửa vượt lên trên dải trên và tín hiệu bán khi giá đóng cửa xuống dưới dải dưới.
Để nâng cao chất lượng tín hiệu, chiến lược tích hợp bộ lọc xu hướng SMA(200) (có thể bật hoặc tắt), chỉ cho phép mở vị thế Long khi SMA đang dốc lên và vị thế Short khi SMA đang dốc xuống. Bằng cách kết hợp tín hiệu bứt phá theo biến động của Bollinger Bands với xác nhận xu hướng dài hạn, chiến lược hướng tới việc giảm thiểu các tín hiệu phá vỡ giả trong giai đoạn thị trường đi ngang, đồng thời tận dụng các xu hướng intraday kéo dài. Ngoài ra, chiến lược còn bao gồm các tùy chọn Stop Loss, Take Profit, bộ lọc khung thời gian giao dịch, cơ chế tự động đóng toàn bộ vị thế khi kết thúc phiên, cùng với điều kiện thoát lệnh khi xu hướng SMA đảo chiều, nhằm đảm bảo quản trị rủi ro một cách chặt chẽ và có kỷ luật.
Cài đặt & cấu hình chiến lược:
Biểu đồ: khuyến nghị khung 5 phút
Khối lượng giao dịch: 3 hợp đồng
Chu kỳ Bollinger Bands: 20
Hệ số nhân Bollinger Bands: 2.0
Chu kỳ SMA: 200
Cắt lỗ: 10 điểm
Chốt lời: tắt
Bộ lọc xu hướng SMA: Bật / Tắt
Dùng chốt lời: Bật / Tắt
Bộ lọc giờ: Bật / Tắt
Khung giờ giao dịch: 09:00 – 14:30
Chiều giao dịch: Mua / Bán / Cả hai
Cài đặt mặc định của script:
Chiến lược tính toán Bollinger Bands dựa trên đường SMA(20) của giá đóng cửa. Dải trên và dải dưới được tạo bằng cách cộng hoặc trừ hai độ lệch chuẩn quanh đường giữa.
Khi biến động tăng mạnh, hai dải Bollinger Bands sẽ mở rộng. Khi thị trường đi ngang hoặc biến động thấp, hai dải sẽ co hẹp lại.
Khi giá đóng cửa vượt lên trên dải trên Bollinger Bands, lực mua có thể đang chiếm ưu thế. Khi giá đóng cửa phá xuống dưới dải dưới Bollinger Bands, lực bán có thể đang chiếm ưu thế.
Khi bật bộ lọc xu hướng SMA(200), script chỉ cho phép lệnh Mua khi SMA(200) dốc lên và chỉ cho phép lệnh Bán khi SMA(200) dốc xuống. Khi tắt bộ lọc SMA, chiến lược có thể giao dịch cả hai chiều chỉ dựa trên tín hiệu breakout của Bollinger Bands.
Người dùng có thể thêm chỉ báo Bollinger Bands có sẵn trên TradingView với tham số Length 20 và Multiplier 2.0 để quan sát tín hiệu trực quan trên biểu đồ giá.
Điều kiện vào và thoát lệnh:
Vào lệnh Mua:
Giá đóng cửa > dải trên Bollinger Bands
VÀ SMA(200) dốc lên, nếu bật bộ lọc SMA
VÀ tín hiệu xuất hiện trong khung giờ giao dịch
VÀ chiều giao dịch cho phép lệnh Mua
Thoát lệnh Mua:
Cắt lỗ: 10 điểm từ giá vào lệnh
Chốt lời: không dùng theo mặc định
Giá đóng cửa chạm hoặc phá xuống dải dưới Bollinger Bands
SMA(200) đảo chiều xuống, nếu bật bộ lọc SMA
Đảo chiều khi xuất hiện tín hiệu Bán hợp lệ
Tự động đóng lệnh khi hết khung giờ giao dịch
Vào lệnh Bán:
Giá đóng cửa < dải dưới Bollinger Bands
VÀ SMA(200) dốc xuống, nếu bật bộ lọc SMA
VÀ tín hiệu xuất hiện trong khung giờ giao dịch
VÀ chiều giao dịch cho phép lệnh Bán
Thoát lệnh Bán:
Cắt lỗ: 10 điểm từ giá vào lệnh
Chốt lời: không dùng theo mặc định
Giá đóng cửa chạm hoặc phá lên dải trên Bollinger Bands
SMA(200) đảo chiều lên, nếu bật bộ lọc SMA
Đảo chiều khi xuất hiện tín hiệu Mua hợp lệ
Tự động đóng lệnh khi hết khung giờ giao dịch
Tuyên bố rủi ro:
Giao dịch hợp đồng tương lai có mức độ rủi ro cao và giá có thể biến động mạnh. Script này chỉ phục vụ mục đích tham khảo, nghiên cứu và kiểm thử. Người dùng cần hiểu rõ giao dịch phái sinh, khẩu vị rủi ro cá nhân và logic của chiến lược trước khi áp dụng vào giao dịch thực tế.
Mọi quyết định đầu tư thuộc trách nhiệm của người dùng. phaisinh.online không chịu trách nhiệm cho bất kỳ khoản lỗ nào phát sinh từ việc sử dụng chiến lược này trong giao dịch thực tế. Hiệu quả trong quá khứ không đảm bảo kết quả trong tương lai.
กลยุทธ์

Entry Point X500Entry Point X500 is an overlay envelope built on Nadaraya–Watson kernel regression with a Gaussian kernel. It smooths price into a local estimate of the underlying trend, draws volatility bands around that estimate using mean absolute deviation (MAD), and marks mean-reversion events when price interacts with those bands.
What makes it useful
Standard moving averages weight bars with fixed linear or exponential schemes. This script estimates price with a Gaussian kernel: bars closer to the estimation point receive higher weight, which helps reduce noise while still reacting to genuine structure changes.
Two calculation modes are included:
Fixed mode (default, non-repainting) — endpoint-anchored regression using past bars only. Historical bands and signals stay fixed after a bar closes. Use this mode for chart review, backtesting logic, and alerts.
Live mode (repainting) — full-window Nadaraya–Watson smoothing recalculated on every update of the last bar. The envelope can use a symmetrical neighborhood of bars around each point inside the lookback window. This can look smoother and more “responsive” on the current chart, but historical lines and signals may appear, move, or disappear as new data arrives.
How it works
Smoothing — a Gaussian kernel weight is applied across the lookback window to produce a regression estimate of price.
Bands — an envelope is built around the estimate using the mean absolute deviation of price from that estimate, scaled by the Deviation Multiplier. MAD reacts less aggressively to extreme outliers than a standard-deviation band.
Signals
Fixed mode: ▲ when close crosses under the lower band; ▼ when close crosses over the upper band. These mark breakouts into potential oversold/overbought extremes for mean-reversion context.
Live mode: ▲ when price returns inside the envelope from below the lower band; ▼ when price returns inside from above the upper band. These mark the start of a local move back toward the regression estimate.
A status label shows whether Live or Fixed mode is active.
Inputs
Kernel bandwidth — controls smoothness. Lower values follow price more closely; higher values create a slower, smoother filter.
Deviation multiplier — controls envelope width.
Price source — series used for the regression (default: close).
Live mode (repaints) — switches between Live and Fixed calculation. Default is OFF.
Live alert: last N bars — in Live mode, alerts fire only for newly appeared signals within the last N bars, to reduce noise while history is recalculated.
How to use
Use the envelope as a contextual overbought/oversold framework for mean-reversion analysis:
Price outside the bands = stretched relative to the local kernel estimate.
Signals highlight interactions with the bands; they are not standalone trade instructions.
Prefer Fixed mode when validating behavior historically or attaching alerts.
Treat Live mode as a real-time visual aid only, and always assume past signals can change.
Confirm with market structure, levels, volume, or other independent context. Do not trade the triangles alone.
Limitations (important)
Live mode repaints. Historical envelopes and triangles are redrawn on each last-bar update and must not be judged as stable historical signals.
Fixed and Live modes use different estimation methods and different signal rules; results will not match 1:1.
Like any smoothing tool, the script can lag or produce frequent signals in choppy markets, and fewer/later signals when bandwidth or deviation is high.
Non-standard chart types (Heikin Ashi, Renko, etc.) can distort signal interpretation; use standard candlesticks/bars for signal analysis.
Disclaimer
This script is for educational and analytical purposes only and does not constitute financial advice. Past visual behavior does not guarantee future results. Test settings carefully on historical data in Fixed mode before considering any real-money use. อินดิเคเตอร์

Regression Trend [MiesOnCharts]Regression Trend - Mies
What it does
This indicator fits a linear regression line to price over a rolling window and draws a corridor around it based on the statistical error of that fit. The corridor is what decides the trend state. As long as price stays inside it, nothing changes. When price closes outside one side, the whole thing flips color and a triangle marks the bar.
The result is a trend line that carries its own tolerance band with it, so you can see at a glance both where the fitted trend sits and how much room price has before the state changes.
How it works
A least squares regression is fitted across the lookback window. That gives the center line.
Around it, the script computes the standard error of the estimate, which is the typical distance between actual price and the fitted line. It comes from the correlation between price and time:
r is the correlation of the source with bar index over the window
residual variance is the price variance scaled by (1 - r²)
the standard error is the square root of that, adjusted for the degrees of freedom of the fit.
This is the part that makes the corridor behave differently from a standard deviation band. The width responds to how well price is actually tracking the trend, not just to raw volatility. A strong, clean trend produces a high correlation, small residuals, and a narrow corridor, so the indicator stays sensitive.
Choppy price that wanders around the line produces a weak fit, a wide corridor, and a much higher bar for triggering a state change. The indicator effectively demands more evidence in exactly the conditions where evidence is thin.
The bands sit at the center line plus and minus a multiple of that standard error. A close above the upper band turns the state bullish, a close below the lower band turns it bearish, and everything in between leaves the previous state untouched. That hysteresis is intentional. It is what stops the indicator from flipping every time price crosses its own mean.
On the chart
Regression line, green when the state is bullish, red when bearish, gray before the first breakout
Upper and lower standard error bands with a light fill between them, colored to match the current state Triangle below the bar when the state flips bullish Triangle above the bar when the state flips bearish.
Display controls to hide the fill, or the bands entirely, if you want a bare trend line
Two alert conditions, one for each direction
Settings
Source sets which series gets fitted. Close is the standard choice. HL2 or a smoothed input will give a calmer line and fewer flips.
Regression Window sets how many bars the fit covers. Shorter windows follow recent structure and react fast. Longer windows describe the broader trend and produce fewer, slower signals. This is the main setting for matching the tool to your timeframe.
SE Band Multiplier controls how far price has to move from the fitted line before the state changes. Lower values tighten the corridor and generate more signals. Higher values require a more decisive break and filter more noise, at the cost of entering later.
Display group toggles the bands and the fill, and adjusts band opacity.
How to use it
The most direct use is as a trend filter. Trade only in the direction the line is colored and treat the opposite flip as your exit or your cue to step aside.
The corridor itself gives you two readable things. Its width tells you how well price is respecting the trend, so a corridor that has narrowed over recent bars means the fit is tightening and the move is orderly. A corridor that has ballooned means the fit has broken down and the state you are looking at is stale. The center line works as a dynamic reference within an established regime, since a pullback toward it is price returning to its own fitted mean rather than to an arbitrary level.
It pairs well with a volume or momentum check. A corridor break tells you the move is statistically unusual relative to the current fit, but it says nothing about whether there is participation behind it.
Behavior worth understanding
The regression is recalculated on every bar, and the corridor plotted on each bar is that bar's own fit. This is a running envelope, not a fixed channel anchored to a pivot, so the bands will look wavier than a manually drawn regression channel. The reference moves with price, which is what keeps the state stable through a sustained run.
Signals are evaluated on the live bar, so a flip can appear and then vanish before the bar closes. Wait for bar close if you need signals that hold.
Limitations
Linear regression assumes price is moving in a straight line across the window, which is never fully true. The fit degrades at sharp reversals and around gaps, and the corridor is slow to acknowledge a turn right after a strong move because that extension is still inside the window. Treat this as a description of current trend structure, not a forecast.
Disclaimer
The indicator provided is not financial advice. Always conduct your own research and consider multiple factors before making trading decisions. Trade at your own risk. อินดิเคเตอร์

Log Regression Regime Channel Log Regression Regime Channel
A market regime, trend quality, price deviation, and directional momentum indicator built around a unified log-linear regression model.
The indicator is designed to evaluate five connected aspects of market behavior:
1. Is the current market statistically directional or neutral?
2. How well does the regression model describe recent price movement?
3. Where is the current price relative to its fitted trend?
4. Does short-term momentum support or oppose the current market regime?
5. Is the underlying regression trend strengthening, cooling, or remaining stable?
The indicator’s primary purpose is to organize several related measurements into one coherent analytical framework.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📐 Core Calculation: Log-Linear Regression
The script applies ordinary least-squares linear regression to the logarithm of closing prices over the selected Regression Length.
The model has the following form:
log(price) = intercept + slope × time
Using logarithmic prices allows the model to analyze proportional price movement rather than absolute movement in price units.
For example, a move from 10 to 11 is treated consistently with a move from 100 to 110 because both represent a 10% change.
After the regression is calculated in logarithmic space, the fitted values are converted back into regular price values using the exponential function.
The model calculates:
• Regression Slope — determines the direction of the fitted trend.
• Regression Intercept — defines the position of the fitted path.
• Residual Standard Deviation — measures the typical distance between observed log prices and the regression model.
• R² — measures how much of the variation in log prices is explained by the fitted trend.
• Fitted Price Values — represent the model values at the beginning and end of the regression window.
Only positive price observations can be used because the logarithm of zero or a negative value is undefined.
The indicator begins displaying the complete model after enough valid historical bars have accumulated.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Residual-Based Regression Channel
The channel width is not calculated from ATR, a fixed percentage, or the standard deviation of raw prices.
It is based on the standard deviation of regression residuals in logarithmic space.
A residual is the difference between:
the observed logarithmic price
and
the logarithmic price fitted by the regression model.
The channel includes:
• Regression Midline — the centerline of the current fitted model.
• Inner Residual Bands — the inner residual-deviation boundaries.
• Outer Residual Bands — the outer residual-deviation boundaries.
• Channel Ribbons — optional shaded areas between the inner and outer boundaries.
Because the boundaries are symmetrical in logarithmic space, they represent proportional deviations from the fitted model.
After conversion back into regular price values, the upper and lower parts of the channel may not appear perfectly symmetrical on a linear price scale.
Difference Between the Two Length Settings
Regression Length determines how many bars are used to calculate the statistical model.
Visible Channel Length determines only how many recent bars are used to draw the current channel.
Changing Visible Channel Length does not change the underlying regression calculation. It changes only the displayed length of the channel.
This separation makes it possible to use a longer model window without drawing the channel across the entire calculation period.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Price Deviation From the Model
Current price deviation is calculated as:
current logarithmic residual ÷ residual standard deviation
The result shows the current price’s distance from the regression model in residual standard deviations.
Price Location
Center — price is close to the fitted regression midline.
Upper — price is above the regression model.
Lower — price is below the regression model.
Deviation Zones
Normal — the absolute deviation remains inside the inner boundary.
Extended — the absolute deviation has reached the inner boundary.
Extreme — the absolute deviation has reached the outer boundary.
The Extended and Extreme states describe price location relative to the current model.
They do not automatically imply that price must reverse. During a strong trend, price may remain elevated or depressed relative to the regression path for an extended period.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 Trend Quality and Trend Strength
The market is not classified as Bullish or Bearish from the direction of the regression slope alone.
The regime engine evaluates three characteristics together:
• the direction of the log-regression slope;
• Trend Quality;
• standardized Trend Strength.
Trend Quality
Trend Quality is measured using R² and displayed as a percentage.
R² indicates how consistently the movement of log prices is described by the regression model.
A higher value means that the fitted trend explains a larger proportion of the observed log-price variation.
Trend Strength
Trend Strength is calculated as the total fitted logarithmic movement across the regression window divided by the residual standard deviation.
It measures how large the directional move is relative to the normal dispersion of price around the model.
The value is expressed in residual standard deviations.
Why Both Measurements Are Used
A small but orderly slope and a large but irregular price movement do not represent the same market condition.
Using R² and Trend Strength together allows the indicator to evaluate:
• the consistency of the trend;
• the magnitude of the directional move;
• the amount of residual noise around the model.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔄 Market Regime Hysteresis
The script maintains one of three persistent market states:
🟢 Bullish
The regression slope is positive, while trend quality and strength satisfy the required thresholds.
⚪ Neutral
The conditions for a directional regime are not satisfied or are no longer sufficiently stable.
🔴 Bearish
The regression slope is negative, while trend quality and strength satisfy the required thresholds.
Different thresholds are used to enter a new directional regime and to preserve an existing regime.
Entering a New Regime
A new Bullish or Bearish regime must satisfy the stricter:
• Trend Entry Quality threshold;
• Trend Entry Strength threshold.
Preserving an Existing Regime
Once a directional regime has been established, it may remain active using the lower:
• Trend Exit Quality threshold;
• Trend Exit Strength threshold.
This mechanism is known as hysteresis.
It reduces frequent switching between directional and neutral states when the model measurements fluctuate around a single threshold.
Market Regime changes are committed only after the chart bar is confirmed. The persistent regime state therefore does not change while the current bar is still forming.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Directional Momentum
Current Momentum is not based on a standard RSI, MACD, or moving-average crossover.
It combines two normalized components:
1. Logarithmic Price Velocity
Measures the direction and speed of proportional price changes.
2. Residual-Deviation Velocity
Measures whether price is gaining or losing ground relative to the fitted regression path.
This makes it possible to distinguish between:
• absolute price movement;
• movement relative to the current statistical trend.
Each component is normalized by its own typical absolute movement.
Momentum Score Composition
75% — normalized logarithmic price velocity.
25% — normalized residual-deviation velocity.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧭 Adaptive Momentum Threshold
Momentum is classified using a dynamic threshold.
The script selects the larger of:
• the user-defined Minimum Momentum Threshold;
• the recent standard deviation of Momentum Score multiplied by the Adaptive Noise Multiplier.
When the Momentum Score becomes more unstable, the classification threshold automatically increases.
This helps reduce directional classifications during periods of elevated momentum noise.
Momentum Classification
🟢 Bullish Momentum — Momentum Score is above the positive adaptive threshold.
🔴 Bearish Momentum — Momentum Score is below the negative adaptive threshold.
⚪ Neutral Momentum — Momentum Score remains between the positive and negative thresholds.
Regression Line Color
A green line represents Bullish Momentum.
A red line represents Bearish Momentum.
A neutral-colored line indicates that momentum has not exceeded the adaptive threshold.
The optional Momentum Fill is drawn between the current fitted regression value and its smoothed reference line. Its color follows the current momentum classification.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 Trend Acceleration
Trend Acceleration measures changes in the standardized regression slope.
The regression slope is first divided by the residual standard deviation.
The change in this standardized slope is then:
• smoothed;
• compared with its typical absolute change;
• converted into a normalized acceleration score.
Interpretation During a Bullish Regime
Strengthening — positive acceleration exceeds the selected threshold.
Cooling — negative acceleration exceeds the threshold in absolute terms.
Stable — the change remains within the threshold.
Interpretation During a Bearish Regime
Strengthening — negative acceleration exceeds the selected threshold.
Cooling — positive acceleration exceeds the selected threshold.
Stable — the change remains within the threshold.
Interpretation During a Neutral Regime
Changing — the absolute change in the standardized slope exceeds the threshold.
Stable — the change remains within the threshold.
Trend Acceleration describes changes in the regression trend and is calculated separately from short-term directional momentum.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧩 Market Phase Engine
Market Phase is an interpretation layer that combines three measurements:
• confirmed Market Regime;
• current Current Momentum;
• current Price Deviation.
Market Phase is not a separate independent indicator and does not use an additional hidden calculation.
It describes the current combination of conditions already calculated by the model.
🟢 Bullish Regime Phases
Bullish Overextension — price has reached an extreme upper deviation during a Bullish regime.
Pullback Recovery — price is in the lower part of the channel, while directional momentum has turned Bullish again.
Bullish Pullback — price has moved into the lower part of the channel while short-term momentum remains Bearish.
Trend Continuation — the Bullish regime is supported by Bullish momentum.
Momentum Cooling — the Bullish regime remains active, but current momentum is Bearish.
Bullish Consolidation — the Bullish regime remains active without a clear directional momentum classification.
🔴 Bearish Regime Phases
Bearish Overextension — price has reached an extreme lower deviation during a Bearish regime.
Bounce Rejection — price is in the upper part of the channel, while directional momentum has turned Bearish again.
Bearish Bounce — price has moved into the upper part of the channel while short-term momentum remains Bullish.
Trend Continuation — the Bearish regime is supported by Bearish momentum.
Countertrend Bounce — the Bearish regime remains active, but current momentum is Bullish.
Bearish Consolidation — the Bearish regime remains active without a clear directional momentum classification.
⚪ Neutral Regime Phases
Upper Price Shock — price has reached an extreme upper deviation without an established directional regime.
Lower Price Shock — price has reached an extreme lower deviation without an established directional regime.
Neutral Upward Impulse — Bullish momentum has developed while the market regime remains Neutral.
Neutral Downward Impulse — Bearish momentum has developed while the market regime remains Neutral.
No Clear Trend — neither a directional regime nor a significant momentum impulse is present.
Market Phase labels describe the current combination of model conditions. They should be interpreted together with the underlying regime, momentum, and deviation measurements.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💎 Why These Components Are Combined
Log Regression Regime Channel is not a collection of unrelated indicators placed inside one script.
All major components are derived from, or directly connected to, the same log-regression model.
How the Components Are Connected
• The regression slope provides the directional foundation.
• R² evaluates the quality of the same regression model.
• Residual dispersion defines the width of the channel.
• Residual volatility standardizes Trend Strength.
• The current residual produces the Price Deviation measurement.
• Changes in residual deviation contribute to Directional Momentum.
• Changes in the standardized slope produce Trend Acceleration.
• Regime, momentum, and deviation are combined by the Market Phase engine.
The purpose of this architecture is to express direction, model quality, price location, momentum, and acceleration in compatible terms.
This differs from mechanically combining several independent oscillators that use unrelated formulas and scales.
Core Architectural Features
• a unified log-linear regression model;
• a residual-based channel instead of an ATR or fixed-percentage channel;
• combined evaluation of trend quality and trend strength;
• confirmed-bar regime hysteresis;
• normalized price and residual momentum;
• an adaptive momentum threshold;
• a separate trend-acceleration measurement;
• deterministic Market Phase classification.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🖥️ Dashboard
The dashboard contains six primary measurements.
Market Regime
Displays the confirmed market state:
Bullish, Neutral, or Bearish.
Trend Quality
Displays:
• R² as a percentage;
• standardized Trend Strength.
Price Deviation
Displays:
• whether price is above or below the model;
• the current deviation in residual standard deviations;
• the Normal, Extended, or Extreme deviation zone.
Current Momentum
Displays the current short-term directional momentum:
Bullish, Neutral, or Bearish.
Trend Acceleration
Displays the current regression-trend state:
Strengthening, Cooling, Stable, or Changing.
Market Phase
Displays the current interpretation of the combination of:
• market regime;
• directional momentum;
• price deviation.
The channel boundaries and regime label use the color of the confirmed Market Regime.
The rolling regression line uses the color of Current Momentum.
These colors represent different calculations and should not be interpreted as duplicate classifications.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ Default Settings
Regression Model
Regression Length — 120 bars
The number of bars used to calculate the log-linear regression model.
Visible Channel Length — 100 bars
The number of recent bars used to display the current regression channel.
Residual Channel
Inner Residual Band — 1.0σ
The inner channel boundary, measured in residual standard deviations.
Outer Residual Band — 2.0σ
The outer channel boundary, measured in residual standard deviations.
Regime Detection
Trend Entry Quality — 45% R²
The minimum model quality required to enter a Bullish or Bearish regime.
Trend Exit Quality — 35% R²
The minimum model quality required to preserve an existing directional regime.
Trend Entry Strength — 1.25σ
The minimum standardized trend strength required to enter a directional regime.
Trend Exit Strength — 0.90σ
The minimum trend strength required to preserve the current regime.
Directional Momentum
Momentum Length — 5 bars
The smoothing period used for short-term directional momentum.
Momentum Baseline — 18 bars
The period used to estimate typical price and residual movement.
Momentum Noise Window — 40 bars
The period used to estimate variation in the combined Momentum Score.
Minimum Momentum Threshold — 0.35
The minimum normalized threshold required for a directional momentum classification.
Adaptive Noise Multiplier — 0.30
The multiplier used to increase the momentum threshold when Momentum Score becomes more unstable.
Acceleration Threshold — 0.35
The minimum normalized change in slope required for an acceleration classification.
Built-In Parameter Safeguards
The script automatically controls relationships between dependent settings:
• the outer residual band remains wider than the inner band;
• exit thresholds cannot be stricter than their corresponding entry thresholds;
• Momentum Baseline remains longer than Momentum Length.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 How to Use the Indicator
The following sequence provides a structured way to interpret the model.
Step 1. Identify Market Regime
Determine whether the model currently recognizes:
• a Bullish regime;
• a Bearish regime;
• a Neutral environment.
Step 2. Evaluate Trend Quality
Use R² and Trend Strength to assess:
• how consistently price is moving;
• how large the fitted trend is relative to residual noise.
Step 3. Determine Price Location
Price Deviation shows:
• whether price is above or below the regression model;
• whether the deviation is Normal, Extended, or Extreme.
Step 4. Compare Momentum With Market Regime
When regime and momentum point in the same direction, the short-term movement is aligned with the broader statistical regime.
When they point in opposite directions, short-term movement is not supporting the current regime.
Step 5. Evaluate Trend Acceleration
Determine whether the current regression trend is:
• Strengthening;
• Cooling;
• Stable;
• Changing.
Step 6. Use Market Phase as the Combined Context
Market Phase combines regime, momentum, and price location into one descriptive classification.
It is best interpreted as a summary of the current market structure rather than separately from its underlying components.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🛠️ How Settings Affect the Model
Regression Length
A longer period generally produces a slower and more stable model.
A shorter period reacts more quickly to price changes but may change market regime more frequently.
Entry Quality and Entry Strength
Higher values require a cleaner and stronger trend before a Bullish or Bearish regime can begin.
Residual Bands
Wider bands require a larger deviation from the regression model before price is classified as Extended or Extreme.
Momentum Thresholds
Higher thresholds reduce the number of Bullish and Bearish momentum classifications.
Acceleration Threshold
A higher threshold reduces the number of Strengthening, Cooling, and Changing classifications.
Settings should be evaluated in relation to the selected instrument, timeframe, and market behavior.
The default values provide a general starting point and are not optimized for every market or timeframe.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ Real-Time Behavior and Limitations
The visible channel represents the latest calculated regression model.
Its boundaries, slope, and shaded areas update as new market data becomes available. The current channel should therefore not be interpreted as a fixed historical object that existed in exactly the same position in the past.
The rolling regression line stores, on each historical bar, the value calculated from the information available at that time.
The Following Values Can Change on an Open Bar:
• regression-model values;
• residual-channel position;
• Price Deviation;
• Current Momentum;
• Trend Acceleration;
• Market Phase.
Market Regime changes only after the bar has been confirmed.
The script does not use future data or lookahead calculations.
However, log regression is sensitive to the selected calculation window.
The model can be materially affected by:
• large price gaps;
• sudden price movements;
• structural market changes;
• low liquidity;
• changes in volatility;
• the selected instrument and timeframe.
The indicator is an analytical tool. Its measurements should be considered together with independent market analysis, risk management, and the characteristics of the selected trading instrument. อินดิเคเตอร์

Fast RSI Divergence at VWAP Signals# Fast RSI Divergence at VWAP Signals
Fast RSI Divergence at VWAP Signals is designed to identify early bullish and bearish RSI divergences while combining them with VWAP Standard Deviation bands to help highlight potential areas of price exhaustion.
Unlike traditional pivot-based divergence indicators that require multiple bars of confirmation, this script uses a dynamic reference-point approach. This allows divergences to be detected earlier while providing optional candle-close confirmation for traders who prefer additional validation.
## Features
• Fast bullish and bearish RSI divergence detection
• Dynamic reference-point algorithm instead of delayed pivot confirmation
• Daily anchored VWAP with configurable Standard Deviation bands
• Optional VWAP deviation filter
• Choice of wick-based or close-based divergence detection
• Optional candle-close confirmation
• Optional RSI momentum turn confirmation
• Optional candle direction confirmation
• Adjustable cooldown between consecutive signals
• Optional display of divergence reference points
• Built-in BUY and SELL alerts
## How It Works
The indicator continuously monitors RSI for overbought and oversold conditions.
When RSI reaches an extreme, a reference point is created. Instead of waiting for a confirmed pivot, the script immediately compares subsequent price action against that reference.
A bearish divergence is detected when:
• Price makes a higher high
• RSI forms a lower high
A bullish divergence is detected when:
• Price makes a lower low
• RSI forms a higher low
Additional filters can be enabled to require:
• Price touching or closing outside the selected VWAP Standard Deviation band
• RSI beginning to reverse direction
• Confirmation from candle direction
• Candle-close confirmation before the signal becomes final
After each confirmed signal, the reference point is automatically updated to prevent repeated signals from the same price movement.
## Recommended Usage
This indicator is designed to work best as part of a confluence-based trading approach rather than as a standalone signal generator.
For additional confirmation, it is recommended to use it together with **Bollinger Bands**. Confluence between RSI divergence, VWAP Standard Deviation extremes, and Bollinger Band extremes can help identify areas where price may be statistically extended.
Examples of higher-confluence setups include:
• Bullish RSI divergence occurring near both the lower VWAP Standard Deviation band and the lower Bollinger Band.
• Bearish RSI divergence occurring near both the upper VWAP Standard Deviation band and the upper Bollinger Band.
Additional confirmation from market structure, trend direction, support and resistance, or volume analysis may further improve trade selection.
## Inputs
The indicator provides extensive customization, including:
• RSI Length
• Overbought and Oversold Levels
• Maximum Divergence Lookback
• Minimum RSI Difference
• Minimum Price Extension
• VWAP Standard Deviation Multipliers
• Wick or Close Validation
• Candle Close Confirmation
• RSI Turn Confirmation
• Candle Direction Confirmation
• Signal Cooldown
• Display Options
## Alerts
Two alert conditions are included:
• Fast RSI Divergence BUY
• Fast RSI Divergence SELL
These alerts can be used with TradingView's alert system or external automation.
## Notes
This indicator is intended to highlight potential momentum exhaustion near statistically extended price levels. Divergence signals indicate that momentum and price are no longer moving in sync, but they do not necessarily imply an immediate reversal.
As with any technical analysis tool, signals should be interpreted within the broader market context. No indicator can predict future price movements with certainty.
อินดิเคเตอร์

อินดิเคเตอร์

Apex Turn v4APEX TURN v4: Kalman Snapback with Fee Gate, Trend Guard and Fair Value Take Profit
Apex Turn is a mean reversion tool that hunts exhausted moves and trades the snap back to fair value. It was designed for crypto perpetual futures but works on any liquid market.
HOW IT WORKS
The script runs an adaptive Kalman filter on log price to estimate fair value, drawn as the orange line. The gap between price and fair value is normalized into a z score over a rolling window. When the z score stretches beyond the entry threshold (2.8 by default) and then hooks back toward the mean while still deeply stretched, the engine looks to trade against the extreme. Longs trigger at washed out lows and shorts trigger at blow off highs.
THREE GATES PROTECT EVERY SIGNAL
Gate one is the chop filter. The Kaufman Efficiency Ratio must confirm a ranging market before any mean reversion entry is allowed.
Gate two is the fee gate. The script projects the reward from current price to fair value, converts your maker and taker fees into R units based on the stop distance, and blocks any signal that would not cover all fees plus a minimum net gain of 0.35R. Blocked signals print as small gray crosses so you can see exactly what fees would have eaten.
Gate three is the strong trend guard. Fair value drift is measured in ATR per bar. When drift is strong, counter trend signals are suppressed until the market prints a release event: a momentum divergence on the z score, volume absorption at the extreme, or both together depending on the mode you select. Trend blocked signals print as orange squares and release events print as aqua diamonds.
EXITS
On entry the script freezes the current fair value as the take profit target, plotted in green, and places the stop in red at 1.5 ATR from entry. The default exit mode assumes you rest a reduce only limit order at the target so your winning exit pays the lower maker fee. Mean touch and overshoot exit modes are also included in the settings. A time stop closes stale positions after 45 bars.
ADAPTIVE ATR
The ATR length is anchored to real time rather than a fixed bar count. It always measures roughly 112 minutes of volatility, so stops, targets and fee math stay consistent whether you chart 30 seconds or 4 hours.
ALERTS
Four webhook ready alerts are included. Entry alerts carry the close price, the stop, the frozen take profit and the projected net R, so an automated system can place the full bracket the moment a position is born. Exit alerts fire for stop, target and time stop events.
SUGGESTED USE
Developed and tested for the 8 minute chart on liquid perpetual pairs. The 30 minute and 1 hour charts also suit the logic well. Timeframes under 5 minutes are not recommended because trading fees consume most of the edge there. Set the maker and taker fee inputs to match your own exchange tier before trusting the fee gate.
Signals are evaluated at bar close and do not repaint. Nothing in this script is financial advice and past behavior in testing does not guarantee future results. Always size positions responsibly and manage your own risk. อินดิเคเตอร์

[Quadapt] Machine Learning Trader Machine Learning Trader
A multi-component Pine Script v6 trading assistant combining a kernel-regression MLMA trend model, dual-length signal envelopes, order block context, retest scoring, adaptive Fibonacci targets, stop loss projection, signal quality filtering, and optional webhook automation.
## Description
Machine Learning Trader is a full-featured market structure and signal confluence indicator built around a Machine Learning Moving Average (MLMA) trend model. It is designed to help traders analyze trend direction, signal quality, order block context, potential retest areas, and adaptive take-profit / stop-loss levels from one chart overlay.
The script is not a black-box strategy or a guaranteed signal generator. It is a discretionary analysis tool that combines several independent market-context modules into one workflow so traders can compare trend, volatility, structure, momentum, and risk levels before making a decision.
### What Makes This Script Different
The core of the indicator is a kernel-regression MLMA engine. Instead of using only a classic moving average, the script builds a regression-style trend estimate using configurable kernel functions and regression modes. This produces a smoothed adaptive trend line and cloud that can be used as a directional context filter.
The MLMA is combined with:
- dual-length nonlinear signal envelopes,
- market structure and order block detection,
- intelligent retest scoring,
- adaptive Fibonacci take-profit projection,
- stop-loss projection,
- multi-timeframe MLMA trend alignment,
- signal quality filtering,
- clustering prevention,
- market regime adaptation,
- optional webhook payload generation.
The result is a confluence-focused indicator: a buy or sell marker is not treated as useful by itself. It is evaluated against the MLMA trend, recent order blocks, volatility regime, momentum, volume, cloud position, and multi-timeframe alignment.
### MLMA Trend Engine
The MLMA module calculates a machine-learning-inspired moving average using kernel methods. The script supports several kernel types, including:
- RBF,
- Linear,
- Polynomial,
- Sigmoid,
- Laplacian,
- Matern,
- Periodic,
- Trigo.
The regression mode can be configured as:
- GPR,
- KRR,
- KPCR,
- SVR,
- Kernel Smoothing,
- Adaptive RQ.
The MLMA output forms the main trend reference. The script also builds upper and lower MLMA bands using an error envelope derived from average absolute deviation around the MLMA output. These bands are used for the cloud, trend state, signal validation, and context scoring.
When the MLMA state is bullish, the script treats price behavior above or near the bullish support side of the cloud as more constructive. When the MLMA state is bearish, the script treats price behavior below or near the resistance side of the cloud as more defensive.
### Instrument-Agnostic Envelope Logic
The signal envelope section is designed to work across instruments with very different price scales, including forex pairs, JPY pairs, metals, oil, gas, indices, and crypto. The nonlinear envelope transform keeps the original algorithmic shape, but price distance is normalized relative to the instrument's local price level before the transform and restored back into price units afterward.
This matters because a raw price move on EURUSD, GBPJPY, XAUUSD, or XNGUSD has a very different numerical size. Normalizing the envelope distance helps the signal engine behave more consistently across instruments instead of being tuned only for one price scale.
### Dual-Length Signal Engine
The script calculates two separate signal envelopes:
- Primary Length: the slower, broader signal model.
- Secondary Length: the faster signal model.
The dual-length system can run in three modes:
- Independent: either length can produce a signal.
- Consensus: both lengths must agree.
- Primary Priority: only the primary length drives the final signal.
This allows traders to choose between sensitivity and confirmation. Independent mode produces more signals, consensus mode is stricter, and primary priority keeps the chart focused on the slower model.
Signal labels can show regular and stronger buy/sell conditions. When both lengths align in Independent mode, the script can also mark BOTH signals.
### Order Block Detection
The order block module searches for volatility-based bullish and bearish blocks using candle direction, volatility expansion, momentum, optional volume confirmation, and trend alignment. Blocks can be displayed as chart boxes with volume and quality information.
Order block detection includes configurable controls for:
- volatility method,
- volatility length,
- smoothing length,
- minimum separation between blocks,
- maximum blocks per direction,
- consolidation filtering,
- trend filtering,
- volume filtering,
- momentum filtering,
- block display style.
The script assigns order block quality using factors such as block size, directional pressure, displacement, market structure, MLMA trend context, and volume. Higher-quality blocks can be emphasized while weaker blocks can be faded.
### Retest Detection
The retest engine evaluates whether price has returned to a recent order block in a meaningful way. Retests can be scored using:
- block strength,
- clean movement away from the block,
- volume confirmation,
- MLMA trend alignment,
- volatility regime,
- reaction quality near the block.
Retest labels can be displayed as simple `R` markers. Strong and weak retests can be controlled separately, and optional percentage display can show the retest confidence score.
### Adaptive Fibonacci Take Profit Levels
The script can project take-profit levels after valid buy or sell signals. The TP engine supports several methods:
- Dynamic ATR,
- Swing-Based,
- Adaptive Swing,
- Heuristic.
It can display multiple Fibonacci extension targets, optional confluence zones, and TP hit status. The TP table shows the current trade direction, entry reference, target levels, stop loss, and active status.
The TP logic is filtered through MLMA and order block context. For example, a buy signal is considered valid when MLMA context supports the buy, or when price is near a supportive bullish order block. This helps reduce target plotting during low-quality or conflicting conditions.
### Stop Loss Projection
The stop-loss module supports:
- ATR-based stops,
- swing-based stops,
- order-block-based stops,
- percentage-based stops.
Stop levels are plotted only after a valid trade setup is detected. The script also tracks whether price has reached the projected stop or take-profit levels.
### Signal Quality Engine
The signal quality engine scores buy and sell setups before final display. The quality score considers:
- MLMA trend context,
- price position relative to the MLMA,
- multi-timeframe alignment,
- order block support or opposition,
- volume quality,
- volatility regime,
- candle body behavior,
- momentum,
- choppy or no-trade conditions,
- cloud width and MLMA slope,
- recent loss-streak penalty logic.
Signals below the configured minimum score can be filtered out. If desired, rejected signals can also be displayed for research and tuning.
### Advanced Signal Filtering
The script includes adaptive clustering prevention and regime-aware filtering.
Clustering prevention reduces repeated signals in the same area by using a time window, ATR-based price window, decay factor, and maximum cluster count.
Regime-aware filtering adjusts confidence behavior using recent market context, including price movement, volatility trend, and volume trend. This helps the script respond differently in ranging, trending, quiet, and volatile periods.
### Multi-Timeframe Trend Table
The MLMA trend table summarizes the current trend state and several higher/lower timeframe states:
- current chart,
- 15m,
- 30m,
- 1H,
- 4H,
- 1D,
- 1W.
This table is useful for quickly checking whether the current signal is aligned with broader market direction.
### Market Exhaustion
The exhaustion module uses RSI, price extension, momentum change, and volume behavior to identify possible bullish or bearish exhaustion. Exhaustion markers are intended as context warnings, not standalone reversal signals.
### Webhook Automation
Optional webhook alerts can send structured payloads for external automation or journaling. The payload can include:
- symbol,
- ticker ID,
- timeframe,
- event type,
- action,
- account tag,
- risk percent,
- order type,
- entry,
- stop loss,
- TP levels,
- quality score,
- MLMA trend,
- bar time.
Webhook use is optional and should be tested privately before live use.
### Alerts Included
The script includes alert conditions for:
- ML Strong Buy Signal,
- ML Strong Sell Signal,
- ML Buy Signal,
- ML Sell Signal,
- rejected quality signals,
- wedge pattern,
- BOTH length signal,
- bullish order block,
- bearish order block,
- bullish exhaustion,
- bearish exhaustion,
- valid enhanced Fibonacci buy/sell signals,
- invalid buy/sell signals,
- Fibonacci TP hit,
- TP/SL levels set,
- order block retest,
- signal clustering,
- market regime change,
- advanced filtering active.
### How To Use
1. Add the indicator to a clean chart.
2. Start with the default settings.
3. Use the MLMA cloud and trend table to understand directional context.
4. Watch for buy/sell labels only when they align with trend, order block, and quality context.
5. Use order block boxes and retest markers to identify possible reaction zones.
6. Use TP/SL projections as planning references, not as automatic trade instructions.
7. Tune Primary Length, Secondary Length, Signal Mode, and Signal Quality settings for the instrument and timeframe you trade.
8. If using alerts or webhooks, test them on paper or in a private environment first.
### Practical Notes
- Lower lengths are more responsive but can produce more noise.
- Higher lengths are smoother but react later.
- Consensus mode is stricter than Independent mode.
- The Signal Quality Engine can remove many low-context signals.
- The Order Block module is most useful when combined with MLMA trend context.
- TP and SL levels are projections based on the selected method; they are not guarantees that price will reach those levels.
- Exhaustion markers are context warnings and should be confirmed with structure, trend, and volatility.
### Limitations
This indicator does not predict the future. It organizes market context using mathematical filters, kernel regression, volatility logic, order block heuristics, and signal-quality rules. It can still produce false signals, especially during news events, illiquid periods, low-volume sessions, strong trend exhaustion, sudden reversals, or choppy markets.
No indicator should be used alone. Traders should combine this tool with their own risk management, market understanding, and independent confirmation. Past chart behavior does not guarantee future results.
อินดิเคเตอร์

Supply and Demand Zones with Market Structure [Jayadev Rana]Overview
This open-source overlay draws two closely related price-action concepts on a single chart: swing-based supply and demand zones, and market-structure mapping (swing labels, a zig-zag of confirmed swings, and Break of Structure markers). It is a visual analysis aid. It does not generate buy or sell signals, it does not place orders, and it makes no performance claim.
How swings are detected
Every element in the script is anchored to a confirmed swing pivot. Swings are found with symmetric pivots: a swing high requires its high to be the highest of the N bars on its left and the N bars on its right (and the mirror condition for a swing low), where N is the Swing High/Low Length input. Because a pivot needs N bars on both sides to exist, it is only confirmed N bars after the pivot bar. Once a swing is confirmed, its label, zone and zig-zag segment are fixed to that historical bar and do not move or repaint afterwards. The trade-off of this method is a fixed N-bar delay before a swing becomes visible. This is inherent to symmetric pivots and is disclosed here so the behavior is clear.
Supply and demand zones
When a swing high is confirmed, a supply zone is drawn from that swing high down to the top of the swing candle's body. When a swing low is confirmed, a demand zone is drawn from that swing low up to the bottom of the swing candle's body. This anchors each zone on the candle that produced the turning point. Because wick-only zones can be very thin, an optional ATR floor (on by default) gives each zone a minimum thickness equal to a configurable multiple of the 14-period ATR, so zones stay readable across different instruments and timeframes.
Each zone extends to the right until it is mitigated. A supply zone is treated as mitigated when price closes above it; a demand zone when price closes below it. On mitigation the zone is either removed or greyed out, depending on the When a zone is broken input. To respect the platform limit of 500 drawing objects and to keep the chart readable, only the newest N zones per side are retained (the Zones to keep per side input).
Market structure
Swing labels: each confirmed swing is labelled relative to the previous same-side swing. Highs are marked HH (higher high) or LH (lower high); lows are marked HL (higher low) or LL (lower low). Bullish structure (HH, HL) uses the bullish colour and bearish structure (LH, LL) uses the bearish colour.
Zig-zag: consecutive confirmed swings are joined by a line, giving a de-cluttered skeleton of price movement.
Break of Structure (BOS): the most recent confirmed swing high and swing low are tracked as reference levels. The first time price closes above the reference swing high a BOS is marked, and the mirror for a close below the reference swing low. Each level is marked only once.
Dashboard
An optional table in the top-right corner shows the current swing length, the number of active supply and demand zones, and the direction of the last Break of Structure.
Inputs
Structure and Swings: swing length, and toggles for the zig-zag, the swing labels and the BOS markers.
Supply and Demand Zones: master toggle, zones to keep per side, the ATR minimum-thickness option and multiplier, broken-zone handling (remove or grey out), and the right-extension toggle.
Colors: independent fill and border colours for supply, demand and broken zones, the zig-zag colour, and the bullish and bearish structure colours.
Dashboard: show or hide the summary table.
Alerts
Alert conditions are provided for a bullish BOS, a bearish BOS, a new supply zone, and a new demand zone.
How to use it
Supply and demand zones are commonly read as areas where price may react, while market structure (the sequence of HH, HL, LH, LL and BOS events) describes the prevailing trend and its changes. Reading the two layers together, for example a demand zone that coincides with bullish structure or a supply zone that coincides with bearish structure, is one way traders use this kind of tool. This script only draws the levels and the structure. It does not tell you when to enter or exit, and any decision you make is your own.
Originality and scope
This is an original implementation written from scratch. The underlying ideas, namely pivot-based swing detection, supply and demand zones, higher-high and lower-low structure labelling, and break of structure, are long-established public-domain price-action concepts rather than the property of any single author. The purpose of this publication is to combine them into one coherent, fully configurable, non-repainting overlay with readable code and a compact summary dashboard.
Limitations and disclaimer
Swings, and everything derived from them, appear with a fixed N-bar confirmation delay. This is by design and is not an error.
Zone mitigation is evaluated on bar close. On the developing (last) bar, states can still change until the bar closes.
Past behaviour of price around a zone or a structure point does not predict future results. This tool is for education and analysis only and is not financial advice. Test any approach yourself before relying on it. อินดิเคเตอร์

RichmondHillCM - Log-Price Regression Channel V1.2RichmondHillCM - Log-Price Regression Channel V1.2
An OLS linear regression fitted to the logarithm of price, with standard-deviation bands (±1σ / ±2σ / ±3σ) projected around the fitted mean. Because the fit is done in log-space, the channel is geometric — it scales proportionally across very different price levels, which makes it well suited to long-trending instruments like SPY where a raw-price channel would distort.
⚠️ Designed for the WEEKLY (1W) timeframe. The default 252-bar lookback (~5 years of weekly data) and the band logic are tuned for weekly candles. A live banner at the top of the stats table turns red whenever the chart is not on a weekly timeframe.
Features
Log-space regression mean + ±1σ/±2σ/±3σ bands with optional fills
BUY / SELL labels on ±2σ crosses, optional STRONG BUY / SELL on ±3σ
Stats table: each band's price, % distance from current price, and Z-score
Background shading when price is stretched beyond ±2σ / ±3σ
Built-in alert conditions for every band cross and the mean
How to use
Best suited to long-term growth compounders like Google (GOOGL, SPY, NDX). Use it on the weekly (1W) timeframe and set your price axis to logarithmic scale for the bands to line up correctly.
Instrument: growth compounders / steady long-term trenders (e.g. GOOGL, MSFT, SPY)
Timeframe: weekly (1W)
Price axis: log scale (right-click the axis → "Logarithmic")
How to read it: price drifting toward ±2σ/±3σ is unusually far from its own trend; the bands act like a statistical rubber band. Use band touches as context, not standalone entries.
For research and educational purposes only. Not financial advice. อินดิเคเตอร์
