The Oloid (OWMA) Oloid Weighted Moving AverageThe Oloid (OWMA) — Oloid Weighted Moving Average
WHAT IT IS
The Oloid is a trend-following indicator built on the geometry of the oloid — a three-dimensional solid discovered by Paul Schatz in 1929. The oloid is the convex hull of two perpendicular circles, each passing through the center of the other. It is one of the few known solids that develops (unrolls) its entire surface onto a plane while rolling, touching every point of its surface exactly once per cycle — no point is missed, no point repeats.
This indicator translates that geometry into a novel, non-linear moving average: the Oloid Weighted Moving Average (OWMA).
MATHEMATICAL LEGACY
OWMA belongs to the lineage of geometry-inspired data analysis tools:
• Fourier Transform (1822) — decomposition of a signal into circular components.
• Wavelet Transform (1980s) — multi-scale analysis with shaped basis functions.
• OWMA (2026) — weighting of time-series data using the developable surface of a three-dimensional geometric solid.
The key innovation: using the coupling of two perpendicular circles as the weighting kernel. Fourier uses single circles. Wavelets use scaled and shifted basis functions. OWMA uses the interaction of two perpendicular oscillating systems to determine the informational value of each data point.
THE CORE IDEA
Every classic moving average weights bars by time: linearly (WMA), exponentially (EMA), or adaptively by a single volatility measure (KAMA, VIDYA). OWMA weights bars by their position on the oloid's developable surface, determined by two coupled market cycles simultaneously:
• Circle A — Momentum cycle. Each bar's local directional efficiency (a 4-bar Kaufman-style efficiency ratio) maps to an angle on the first circle.
• Circle B — Volatility cycle. Each bar's range relative to the recent average range maps to an angle on the second circle.
The oloid's center-of-mass height at the coupled position (alpha, gamma) is:
h(alpha, gamma) = h_min + dh * (0.5 + 0.5 * sin(2*alpha) * sin(2*gamma))
where h_max = sqrt(2)/2 and h_min = 3*sqrt(3)/8 are the exact geometric height extremes of a rolling oloid. The bar's weight is the INVERSE of this height:
• Bars at turning points (height minimum — the moment the rolling oloid "tips over") receive maximum weight. These are transition bars: pivots, regime changes, structure shifts.
• Bars during smooth rolling (height maximum) receive minimum weight. These are continuation bars, carrying less new information.
The result is a moving average that emphasizes market turning points and de-emphasizes continuation — behavior no linear, exponential, or single-factor adaptive MA produces, because the weight depends on the coupled state of two independent cycles, not on time or one factor alone.
HOW IT WORKS ON THE CHART
1. Oloid Line (center). The visible line does not plot OWMA directly — it tracks OWMA with adaptive speed derived from the oloid's current height. Two refinements prevent lag during strong trends:
— Velocity Lead: when adaptation is slow, the line aims where OWMA is going (target = OWMA + delta-OWMA * lead), like the contact point of an oloid rolling down a slope leading its center of mass.
— Adapt Floor: a strong trend (high efficiency ratio) guarantees a minimum tracking speed — gravity keeps the oloid rolling even at maximum height.
2. Oloid Field. ATR-based dynamic bands around the center line. The field narrows as trend efficiency rises (trending markets get a tighter channel) and widens in chop. Field color reflects price position: green above, red below, gray inside.
3. Energy metric (Data Window / dashboard). Energy = efficiency ratio * range regularity. It measures whether the oloid is "rolling" — whether the market has coherent, structured motion. Energy Up / Energy Down split it by the Oloid Line's slope direction. These values are not drawn as chart lines — they live in the dashboard and the Data Window, where the Pine Screener can also read them.
4. Slope Engine. Tracks the slope of RangeReg Bull% — the percentage of bars in the window that made new highs. The slope is classified as RISING / FLAT / FALLING. A flat-to-rising transition marks "momentum awakening": after a structural pause, bullish breadth resumes.
SIGNALS — TWO INDEPENDENT ENTRY ENGINES
• LONG-SLOPE (Pure Slope — enabled by default): RRB slope transitions flat-to-rising while close is above the Oloid Center. Catches "momentum awakening" — trend starts after a structural pause.
• LONG (OWMA Cross — off by default, optional): close crosses above the upper field boundary, with all filters passing. A dedicated filter blocks these entries while the slope is falling ("tired trend" protection). Enable this engine if you want additional breakout-style entries alongside the slope engine.
• SHORT / CLOSE: mirror logic below the field (part of the OWMA Cross engine, so they appear only when that engine is enabled); in "Long Only" mode a short signal closes the long instead. With the default configuration, positions are closed by the selected exit mode's stop.
Signal filters: an Energy window (default 0–20% — signals are suppressed when momentum is overheated), an optional minimum efficiency ratio, and a cooldown between signals.
EXIT MODES (selectable)
• Wide ATR (default, x3.5): a loose trailing stop that lets winners develop and captures more of the favorable excursion.
• ATR Trail (x2.0): classic tighter trail.
• Slope+Stop: exits when the RRB slope turns falling (momentum exhausting), with a fixed protective stop as the floor.
• Hybrid: fixed protective stop for the first N bars, then an ATR trail activates.
The current trailing stop is plotted as a step-line while a position is open.
HOW TO USE IT
1. Add to any symbol and timeframe. Defaults (Radius 21, Long Only, Pure Slope engine, Wide ATR exit) are a reasonable starting point for daily charts of trending assets.
2. Watch the dashboard (top right): Circle A (trend efficiency), Circle B (volatility state), Energy with its window check, Field width and direction, Slope state, and the active stop level.
3. Higher-quality entries tend to occur when: Energy is in the lower half of the window and rising, volatility (Circle B) is below ~110%, and the Field is narrow or narrowing (squeeze conditions).
4. Pine Screener: the "Energy Up Trend" value is exported to the Data Window — filter "Energy Up Trend between 3 and 20" to scan for symbols entering a sustained bullish momentum phase.
5. Alerts are provided for both entry engines, exits, the Bullish Trend Zone, and slope-state transitions (diagnostic).
INPUTS SUMMARY
• Oloid Geometry: Radius (base period of both circles, default 21), Circle Coupling (0.5 = the oloid's natural geometry), Meander Intensity.
• Signals: mode (Long Only / Short Only / Both), Energy window, minimum ER, cooldown.
• Slope Engine: enable/disable each engine, falling-slope filter, slope smoothing and flat threshold.
• Exit Mode: the four modes described above with their parameters.
NOTES
• The indicator is self-contained: all mathematics is computed from the oloid's parametric geometry (height function, surface development, coupling), plus standard building blocks (ATR, efficiency ratio, SMA/EMA smoothing).
• A square-root recency decay is combined with the oloid surface weight, so the total weighting respects both surface position and recency.
• Signals are generated on bar close and do not repaint: the position state machine uses confirmed values only.
• This is a technical analysis tool, not financial advice. Test on your instruments and timeframes before using signals in live trading.
Indicator

Adaptive Trend Ensemble [BackQuant]Adaptive Trend Ensemble
Overview
Adaptive Trend Ensemble is an online-learning trend filter that combines eight different moving-average methods into one continuously weighted trend estimate.
Instead of selecting one moving average permanently, the indicator treats each method as an independent forecasting expert. Every bar, each expert is evaluated according to whether its previous slope correctly anticipated the direction of the latest price move.
Experts that were directionally correct retain more influence. Experts that were wrong lose influence through a multiplicative penalty. The weights are then normalised and used to blend all eight moving-average values into one adaptive ensemble line.
The indicator therefore attempts to answer two separate questions:
Which smoothing method has recently aligned best with price direction?*
How strongly do the weighted methods currently agree on the direction of trend?
The final output includes:
A dynamically weighted ensemble trend line.
Bullish and bearish trend-state colouring.
A gradient between price and the ensemble.
A consensus-driven glow.
Trend-coloured candles.
A live label showing the leading expert and its current weight.
Alerts when the ensemble trend changes direction.
This is not a fixed moving average and it is not a simple average of several indicators. The contribution of each expert changes over time according to its recent directional performance.
Core idea
Moving averages respond differently to the same market.
A Hull Moving Average may respond quickly during a sharp transition, while an RMA may remain stable through temporary noise. A linear-regression estimate may follow a smooth directional move well, while a conventional EMA may perform better during a more ordinary trend.
No individual smoothing method is consistently superior across every environment.
Markets alternate between:
Persistent trends.
Fast breakouts.
Slow directional drift.
Volatile reversals.
Compressed ranges.
Noisy transitions.
A fixed indicator cannot change its mathematical personality when the environment changes. It continues using the same weighting structure regardless of whether that structure currently suits the market.
Adaptive Trend Ensemble addresses this by maintaining a bank of different smoothing methods and changing their influence through time.
The model does not attempt to decide in advance which method is best. It allows recent realised price action to determine which experts should currently receive more weight.
Prediction with expert advice
The indicator is based on a class of online-learning methods commonly described as:
Prediction with Expert Advice
In this framework:
Several experts produce predictions.
The actual outcome is observed.
Each expert receives a loss based on its prediction.
Expert weights are updated.
The combined model places more influence on better-performing experts.
The term “expert” does not imply that each method is intelligent by itself. An expert is simply an individual forecasting rule.
In this indicator, the eight experts are eight moving-average methods.
The model uses a multiplicative-weights process closely related to the Hedge and Weighted Majority families of online-learning algorithms.
The central principle is:
Do not commit permanently to one model.
Track several models simultaneously.
Reduce the weight of models that make mistakes.
Allow the combined forecast to adapt as relative performance changes.
Online learning
The model learns sequentially, one bar at a time.
It does not train on a separate historical dataset and then freeze its parameters.
At each new bar:
The previous slope of each moving average is treated as that expert's prediction.
The realised close-to-close direction is observed.
Each expert receives a loss.
Weights are updated multiplicatively.
Weights are normalised.
The current expert values are blended using the new weights.
This makes the process online and adaptive.
The weight state is carried forward from bar to bar, meaning the current ensemble reflects the accumulated results of earlier expert decisions.
The expert bank
The ensemble contains eight moving-average experts:
Simple Moving Average - SMA*
Exponential Moving Average - EMA
Weighted Moving Average - WMA*
Hull Moving Average - HMA
Double Exponential Moving Average - DEMA*
Running Moving Average - RMA
Arnaud Legoux Moving Average - ALMA*
Least-Squares Moving Average - LSMA
All experts use the same Base Length.
This is important because it keeps their nominal observation horizon comparable. The ensemble is comparing different mathematical treatments of approximately the same lookback rather than comparing completely unrelated time horizons.
Even with an identical length, the experts behave differently because they assign weight to historical observations in different ways.
Simple Moving Average - SMA
The SMA applies equal weight to every observation inside the selected window.
Its general form is:
SMA = Sum of observations / Number of observations
The SMA is stable and easy to interpret, but every included observation has the same importance.
This can make it slower to react when a new trend begins because older prices continue to influence the average until they leave the window.
Within the ensemble, the SMA acts as a neutral equal-weight baseline.
Exponential Moving Average - EMA
The EMA assigns progressively greater weight to recent observations.
Its recursive form is based on:
EMA = α × Current Price + (1 - α) × Previous EMA
where α is determined by the selected length.
Compared with an SMA of the same length, an EMA generally responds more quickly to recent movement.
Its recursive weighting makes it useful during ordinary directional markets, although it can still turn repeatedly when price oscillates in a range.
Weighted Moving Average - WMA
The WMA assigns linearly increasing weight to more recent observations.
For example, in a simplified four-period WMA, the newest value receives four units of weight, while the oldest receives one.
This makes the WMA more responsive than an equal-weight SMA while retaining a finite lookback window.
Within the ensemble, it provides a direct recency-weighted alternative to the exponential behaviour of the EMA.
Hull Moving Average - HMA
The Hull Moving Average was designed to reduce lag while preserving a relatively smooth output.
Its construction combines weighted moving averages over different horizons, applies a lag-compensation step, and then smooths the result over approximately the square root of the original length.
Conceptually:
Calculate a faster WMA.
Calculate a slower WMA.
Use their difference to compensate for lag.
Smooth the compensated result.
The HMA often reacts quickly to changes in trend direction.
That responsiveness can make it valuable during strong transitions, but it may also make it more sensitive to short-term oscillation.
Double Exponential Moving Average - DEMA
Despite its name, DEMA is not simply an EMA calculated twice.
Its general construction is:
DEMA = 2 × EMA - EMA of EMA
The second EMA estimates some of the lag in the first EMA. Subtracting it attempts to create a smoother with less delay.
DEMA can respond quickly to directional changes, although reduced lag may also increase sensitivity during unstable conditions.
Running Moving Average - RMA
RMA is commonly associated with Wilder-style smoothing.
It uses a slower recursive update than a typical EMA of the same nominal length.
Its general form places substantial influence on the previous RMA value, producing a persistent and stable estimate.
The RMA expert often changes direction less aggressively than the faster methods.
Within the ensemble, it acts as one of the more conservative smoothing models.
Arnaud Legoux Moving Average - ALMA
ALMA applies a Gaussian-style weighting curve across the observation window.
The weighting distribution can be shifted toward more recent observations while maintaining a smooth bell-shaped profile.
The script uses a recent-weighted offset and a fixed Gaussian width.
ALMA attempts to balance:
Smoothness.
Reduced lag.
Controlled weighting of the observation window.
It provides a different weighting structure from the linear, exponential and lag-compensated experts.
Least-Squares Moving Average - LSMA
The LSMA is based on linear regression.
Instead of averaging historical prices directly, it fits a straight line through the selected window and evaluates the regression estimate at the current bar.
The method attempts to represent the local directional path of price.
LSMA can follow smooth trends closely because it models slope explicitly. However, it may respond strongly when the local regression direction changes abruptly.
Within the indicator, the LSMA is produced using the rolling linear-regression output.
Base Length
The Base Length is shared by all eight experts.
Lower values:
Make every expert more responsive.
Increase sensitivity to short-term changes.
Produce faster weight and trend changes.
Increase the possibility of whipsaws.
Higher values:
Create smoother expert outputs.
Focus the ensemble on broader trend structure.
Reduce short-term changes.
Increase lag during sudden reversals.
Because all experts share the same length, changing this setting adjusts the entire ensemble horizon.
It does not change the number of experts or their relative starting weights.
Expert predictions
The model evaluates each expert using the direction of its slope.
For each moving average:
Rising slope is represented as +1.
Falling or non-rising slope is represented as -1.
To evaluate the latest completed move, the script uses the expert's slope from the previous bar.
For example:
If the expert was rising from two bars ago to the previous bar, it predicted a positive current move.
If the expert was falling, it predicted a negative current move.
The realised outcome is determined from the current close relative to the previous close:
Close above previous close = positive realised direction.
Close below previous close = negative realised direction.
Unchanged close = zero realised direction.
The model therefore scores directional slope prediction, not the numerical distance between each moving average and price.
An expert is rewarded for getting direction right, even if its plotted value is relatively far from the market.
Likewise, an expert is penalised for getting direction wrong even if its line remains visually close to price.
Loss functions
The indicator provides two loss functions:
Directional 0/1*
Magnitude-weighted
The selected loss determines how strongly incorrect experts are penalised.
Correct experts receive zero loss under both modes.
Directional 0/1 loss
Directional mode treats every incorrect prediction equally.
The loss is:
0 when the expert predicted the realised direction correctly.
1 when the expert predicted incorrectly.
This means that an incorrect prediction on a very small move receives the same loss as an incorrect prediction on a large move.
Directional mode answers a simple question:
Was the expert right or wrong?
It does not consider how important the move was.
This mode can produce consistent learning because every directional observation is treated equally, but it may respond to small and insignificant price changes as strongly as major moves.
Magnitude-weighted loss
Magnitude-weighted mode scales the penalty according to the size of the realised move.
The move is normalised using ATR:
Move = Absolute close-to-close change / ATR
The ATR uses the shared Base Length.
The incorrect expert's loss becomes:
Loss = Normalised Move
with the magnitude capped at 3.
The cap prevents a single extreme bar from creating an unlimited penalty.
This mode gives greater importance to mistakes during large movements.
For example:
An incorrect expert during a 0.10 ATR move receives a small penalty.
An incorrect expert during a 1.00 ATR move receives a larger penalty.
An incorrect expert during a move above 3 ATR receives the capped penalty of 3.
Magnitude-weighted mode answers:
How costly was the directional mistake relative to current volatility?
This can make the ensemble adapt more strongly after significant movements while paying less attention to small fluctuations.
Flat price bars
If the current close is unchanged from the previous close, the realised direction is zero.
Because expert directions are encoded as either positive or negative, no expert can exactly match a zero realised direction.
Under Directional mode, all experts receive the same incorrect classification.
Because every weight is multiplied by the same penalty factor, their relative weight distribution remains effectively unchanged after normalisation.
Under Magnitude-weighted mode, the realised move is zero, so the resulting penalty is also zero.
In both cases, a completely flat close-to-close bar does not materially change the relative ranking of the experts.
Multiplicative weight update
Each expert begins with an equal weight:
Initial Weight = 1 / 8
After the loss is calculated, the weight is updated using:
New Unnormalised Weight = Old Weight × exp(-η × Loss)
where η is the Learning Rate.
This is the central Hedge or multiplicative-weights update.
Correct experts have zero loss:
exp(-η × 0) = 1
Their unnormalised weight is unchanged.
Incorrect experts have a positive loss, so their weight is multiplied by a value below one.
For example, in Directional mode with a Learning Rate of 2:
Incorrect Weight Multiplier = exp(-2) ≈ 0.135
An incorrect expert retains only about 13.5% of its previous unnormalised weight before the weight set is normalised again.
This does not mean its final displayed weight will necessarily fall by exactly 86.5%, because all expert weights are subsequently rescaled so they sum to one.
Why multiplicative updates are used
An additive system might subtract a fixed quantity from each incorrect expert.
That can create problems:
Weights can become negative.
The same penalty has a different effect on large and small weights.
The model may not adapt proportionally.
A multiplicative update preserves non-negative weights and penalises experts proportionally to their current influence.
It also allows the distribution to become concentrated around consistently successful methods.
Learning Rate - η
The Learning Rate controls how aggressively the ensemble shifts weight after mistakes.
Higher values:
Penalise incorrect experts more strongly.
Move influence rapidly toward recent winners.
Can produce winner-take-all behaviour.
Can make the leader change abruptly after a few important bars.
Lower values:
Produce gradual weight changes.
Keep the expert distribution more diversified.
Reduce sensitivity to short-term performance.
Make the model slower to adapt.
The Learning Rate does not change the moving averages themselves. It changes only how quickly their relative influence evolves.
High Learning Rate behaviour
At high settings, a wrong expert may lose most of its weight after one or two mistakes.
This can be beneficial when one smoothing method is clearly better suited to the current regime.
It can also create instability:
A recent winner can dominate the ensemble.
A temporary performance streak can cause excessive concentration.
The model can switch leaders quickly when conditions reverse.
Low Learning Rate behaviour
At low settings, the ensemble behaves more like a slowly adapting average of the expert bank.
No single observation dramatically changes the distribution.
This produces smoother adaptation, but a poorly suited expert may retain substantial influence for longer.
Weight normalisation
After all expert weights are updated, they are normalised:
Normalised Weight = Expert Weight / Sum of All Expert Weights
This ensures that the complete weight set sums to one.
The weights can then be interpreted as each expert's share of the ensemble.
For example:
A 25% weight means that expert contributes one quarter of the weighted output.
A 5% weight means its current influence is relatively small.
The weights are not probabilities that the experts will be correct on the next bar.
They are adaptive influence coefficients based on accumulated relative loss.
Weight Floor
The optional Weight Floor preserves a minimum allocation for every expert.
After normalisation, the adjusted weight is calculated so that:
Every expert receives at least the selected floor.
The remaining weight is distributed according to the normalised Hedge weights.
The full set continues to sum to one.
For eight experts, a floor of 0.01 reserves at least 1% for each expert.
This assigns:
A minimum combined mass of 8%.
The remaining 92% according to relative performance.
A floor of 0.05 reserves at least 5% for each of the eight experts, using 40% of the total distribution as minimum allocations.
The remaining 60% is distributed according to current performance.
Why use a floor?
Without a floor, repeatedly incorrect experts can approach a weight extremely close to zero.
Because the update only reduces weights after losses, an expert with almost no weight may require a long period of relative outperformance before it becomes influential again.
A positive floor keeps all methods alive.
This allows an expert that performed poorly in the previous regime to recover more quickly when the market environment changes.
Weight Floor set to zero
With a zero floor:
The model is free to concentrate almost entirely in one expert.
Recent winners can dominate strongly.
The ensemble can become highly specialised.
This produces the purest multiplicative-weights behaviour but increases the risk of weight collapse.
Positive Weight Floor
With a positive floor:
The expert bank remains diversified.
Cold experts retain some influence.
The model can recover more easily after regime changes.
The leading expert's maximum possible weight is reduced.
The floor therefore controls the balance between specialisation and diversity.
Ensemble output
After the weight update, the current values of the eight experts are blended:
Ensemble = Sum of Expert Weight × Expert Value
This is a weighted average in which the weights are determined by online directional performance.
If the HMA currently has the greatest weight, the ensemble will behave more like the HMA.
If the RMA and SMA dominate, the output will become smoother and more conservative.
If the weights are distributed evenly, the line represents a broad blend of all eight methods.
The output can therefore change its effective smoothing behaviour without changing the user-selected Base Length.
Line Smoothing
The weighted ensemble may be passed through an optional EMA for visual smoothing.
A setting of 1 effectively disables this additional stage.
Higher settings:
Create a smoother displayed line.
Reduce small slope changes.
Delay bullish and bearish flips.
This smoothing is cosmetic in the sense that it occurs after the online expert weighting.
It does not affect:
Expert predictions.
Expert losses.
Weight updates.
Consensus.
Leader selection.
It does affect the final plotted line and the trend state derived from that line.
Trend state
Trend direction is determined from the slope of the smoothed ensemble line.
If the line is above its previous value, trend becomes bullish.
If the line is below its previous value, trend becomes bearish.
If the line is unchanged, the previous trend persists.
This creates a persistent two-state regime.
A bullish flip occurs when the trend changes from bearish to bullish.
A bearish flip occurs when it changes from bullish to bearish.
The trend state is based on the ensemble's slope, not on price crossing the ensemble.
Price may be above or below the line without immediately changing its direction.
Consensus calculation
The indicator calculates a separate weighted directional vote.
Each expert's current slope direction is multiplied by its current weight:
Weighted Vote = Sum of Weight × Direction
Because each direction is either +1 or -1 and the weights sum to one, the vote lies between -1 and +1.
Examples:
+1 means all meaningful weight is assigned to rising experts.
-1 means all meaningful weight is assigned to falling experts.
0 means bullish and bearish weighted influence is evenly balanced.
The displayed consensus strength is:
Consensus Strength = Absolute Value of Weighted Vote
This converts the result to a range from zero to one.
0% means the weighted expert bank is evenly divided.
100% means the weighted influence is entirely aligned in one direction.
Weighted consensus versus expert count
Consensus is not calculated by simply counting how many of the eight experts are rising.
An expert with a 40% weight contributes more than one with a 2% weight.
For example:
Five low-weight experts may be bullish.
Three high-weight experts may be bearish.
The final weighted vote can still be bearish.
This means consensus measures the agreement of the current weighted model, not the raw number of methods on each side.
With a zero Weight Floor, consensus may become very high when one expert dominates, even if several near-zero-weight experts disagree.
With a positive floor, disagreement from the remaining experts has more influence on the consensus value.
Consensus is not confidence
The consensus percentage should not be interpreted as a probability that the trend will continue.
It measures only the current alignment of weighted expert slopes.
High consensus means:
The influential experts point in the same direction.
It does not guarantee:
Future price continuation.
A profitable entry.
Low reversal risk.
Strong agreement can occur late in a mature trend as well as early in a new one.
Leading method
The live information label identifies the expert with the highest current weight.
It displays:
The expert name.
Its current percentage weight.
The weighted consensus strength.
The current ensemble direction.
For example:
Leading: HMA (34.5%)*
Consensus: 78% ▲
This means the HMA currently has the largest share of the ensemble and the weighted expert bank is strongly aligned upward.
The leader percentage is not a win probability.
It is only the experts share of the current normalised weight distribution.
Leader changes
The leading method can change when:
The current leader makes directional mistakes.
Another expert remains correct while competitors are penalised.
A large magnitude-weighted move strongly changes relative weights.
The market transitions into a regime better suited to another smoother.
Leader changes can help reveal how the ensemble is adapting.
For example:
A shift toward HMA or DEMA may reflect stronger preference for responsive methods.
A shift toward SMA or RMA may reflect better recent performance from slower methods.
A shift toward LSMA may occur during a smooth local directional path.
These interpretations are contextual and should not be treated as fixed rules.
Gradient fill
The indicator fills the area between price and the ensemble line.
When price is above the line:
A bullish gradient is displayed.
When price is below the line:
A bearish gradient is displayed.
The gradient visually separates price from the adaptive trend estimate.
The fill reflects price location, while the line colour reflects the slope-derived ensemble trend.
These can temporarily disagree.
For example:
Price may fall below a still-rising ensemble during a pullback.
Price may rise above a still-falling ensemble during a counter-trend rally.
This disagreement can provide useful context.
Consensus glow
A glow is drawn around the ensemble line.
Its brightness changes according to weighted consensus.
When consensus is high:
The glow becomes brighter and more visible.
When the experts are divided:
The glow becomes more transparent.
The glow width is scaled using ATR based on the Base Length, helping the effect remain proportional across instruments and volatility environments.
The glow is a visual representation of model agreement. It does not modify the line or trend calculation.
Candle colouring
Candles can be coloured according to the current ensemble trend:
Bullish trend uses the selected bullish colour.
Bearish trend uses the selected bearish colour.
Candle colouring is based on the direction of the ensemble line, not the direction of each individual candle.
A bearish candle can therefore remain green during a bullish ensemble regime, and a bullish candle can remain red during a bearish regime.
How to interpret the indicator
Bullish ensemble trend
A bullish state means the final ensemble line is rising.
This indicates that the current weighted combination of experts is moving upward.
It does not require all individual experts to be bullish.
Bearish ensemble trend
A bearish state means the final ensemble line is falling.
The weighted combination is moving downward, even if one or more individual experts remain bullish.
High bullish consensus
A strongly positive vote means most influential expert weight is assigned to rising methods.
This can indicate broad directional alignment.
High bearish consensus
A strongly negative vote means the influential experts are predominantly falling.
Low consensus
A consensus near zero means weighted expert directions are divided.
This can occur during:
Trend transitions.
Sideways ranges.
Pullbacks.
Disagreement between faster and slower methods.
Low consensus does not automatically mean price will remain sideways. It means the ensemble's components are not currently aligned.
High leader weight and high consensus
This indicates that:
One method currently dominates.
The broader weighted bank is aligned with it.
The model is highly concentrated and directionally unified.
This can produce a responsive and decisive ensemble, but it also means the output depends heavily on the current leader.
Distributed weights and high consensus
This means several experts maintain meaningful weights while pointing in the same direction.
The trend is supported by a more diversified group of methods.
Leader weight high but consensus low
This can occur when the dominant expert points one way while several remaining experts point the other way.
The ensemble may still follow the leader, but internal disagreement is present.
How to use the indicator
1. Trend regime filter
Use the ensemble slope as directional context:
Prioritise long setups during bullish regimes.
Prioritise short setups during bearish regimes.
The indicator does not define entry price, stop placement or profit targets.
2. Consensus filter
A user may require stronger consensus before acting on the trend state.
For example:
A bullish flip with low consensus may represent an early or uncertain transition.
A bullish regime with high consensus indicates broader weighted alignment.
No universal consensus threshold is appropriate for every market.
3. Pullback analysis
During a bullish ensemble regime:
Price moving toward or below the line may represent a pullback.
The ensemble remaining bullish suggests its trend estimate has not yet reversed.
During a bearish regime:
Price moving toward or above the line may represent a counter-trend rally.
Price interaction with the line should be combined with structure and risk management.
4. Regime adaptation observation
The Leading Method label can be used to study how different smoothers perform through changing environments.
Rather than assuming one moving average is always best, the user can observe:
Which expert gains weight during trends.
Which expert takes over during transitions.
How concentrated the model becomes.
How quickly weights change under different Learning Rates.
5. Bullish and bearish flips
Trend flips can be used as:
Regime-change alerts.
Confirmation for another setup.
Potential exit conditions.
A directional filter for discretionary trades.
Because flips are based on line slope, responsive settings can generate repeated changes during ranges.
Suggested configurations
Balanced adaptive configuration
Moderate Base Length.
Moderate Learning Rate.
Directional loss.
Small positive Weight Floor.
Minimal Line Smoothing.
This keeps the model adaptive while preserving some expert diversity.
Fast adaptation configuration
Shorter Base Length.
Higher Learning Rate.
Magnitude-weighted loss.
Zero or very small Weight Floor.
Line Smoothing of 1 or 2.
This allows rapid concentration around recent winners but can create unstable leader changes.
Conservative diversified configuration
Longer Base Length.
Lower Learning Rate.
Directional loss.
Positive Weight Floor.
Additional Line Smoothing.
This creates slower and more diversified adaptation.
Large-move-focused configuration
Magnitude-weighted loss can be used when mistakes during large ATR-normalised moves should matter more than errors during minor fluctuations.
This may reduce the influence of small alternating bars on the weight distribution.
Pure directional configuration
Directional loss is useful when every close-to-close directional observation should be treated equally.
It creates a straightforward right-or-wrong scoring process.
How this differs from averaging moving averages
A normal moving-average ribbon or composite may calculate:
Average of SMA, EMA, HMA and other methods.
If every method receives equal weight permanently, its influence never changes.
Adaptive Trend Ensemble instead calculates:
Performance-dependent weights.
Sequential loss updates.
A dynamically changing weighted output.
Two bars with the same expert values can produce different ensemble values if the weight distributions differ.
How this differs from selecting the current fastest average
The indicator does not select whichever moving average is currently closest to price or whichever has moved the most.
Weights are based on whether previous expert slopes correctly anticipated realised price direction.
An expert can therefore lead even if it is not the fastest or closest line.
How this differs from an optimisation
The model does not search historical data for one set of parameters with the best backtest result.
It does not change the shared length of each expert.
Instead, it performs continuous online adaptation of the expert weights.
This avoids permanently selecting one historical winner, but it also means recent performance can strongly influence the current model.
How this differs from a machine-learning forecast
The indicator uses a genuine online-learning algorithm, but it is not a neural network or a price-target forecasting model.
It does not estimate the size of the next move.
The experts make binary directional predictions derived from their slopes.
The learning system then adjusts how much influence each moving-average value receives.
It is therefore best understood as an adaptive model-selection and blending process.
Causality and real-time behaviour
The learning update uses:
The prior-bar slope of each expert.
The current close-to-close realised direction.
It does not use future bars.
On historical completed candles, the update is fully causal.
On the current live candle:
The close can continue changing.
The realised direction can change.
Expert values can change.
Weights and consensus can update intrabar.
A bullish or bearish flip may appear before the candle closes.
Users requiring confirmed signals should evaluate the indicator at bar close.
Strengths
Combines eight distinct smoothing methods.
Adapts expert influence through online learning.
Supports directional and magnitude-sensitive losses.
Uses multiplicative updates rather than fixed weighting.
Provides optional protection against permanent weight collapse.
Separates ensemble direction from expert consensus.
Displays the currently leading method.
Uses one shared horizon for a fairer expert comparison.
Requires no offline training process.
Provides transparent open-source calculations.
Summary
Adaptive Trend Ensemble combines eight moving-average experts using a multiplicative online-learning model.
Each expert uses the same Base Length but applies a different smoothing method. The previous slope of each expert acts as its directional prediction for the latest close-to-close move.
After the realised direction is observed, incorrect experts receive either a fixed directional loss or an ATR-normalised magnitude-weighted loss. Their weights are reduced using an exponential Hedge update, then normalised and optionally adjusted using a minimum Weight Floor.
The current expert values are blended according to these adaptive weights, producing one ensemble line whose effective behaviour changes as different methods gain or lose influence.
A separate weighted vote measures current directional agreement. This consensus controls the visual glow and is displayed beside the current leading expert.
The result is a transparent adaptive trend model that does not assume one moving average will remain optimal. Instead, it continuously redistributes influence toward the methods that have recently aligned better with realised price direction while retaining configurable control over responsiveness, diversity and visual smoothing.
Indicator

Indicator

Dual Phase Swing Trading IntelligenceCredit: This indicator builds upon the Moving Average Shaded Fill Area Crossover concept originally developed by #aballard11. The visual foundation of using EMA fills to represent trend structure was inspired by their pioneering work in making multi-timeframe trend analysis accessible through clean chart visualization. This implementation has been significantly expanded and rebuilt by The Scalping Ant to create a dual-phase trend system specifically engineered for swing trading on higher timeframes, adding candle coloring logic, dual-signal generation, non-repainting confirmation modes, and real-time dashboard analytics.
WHAT THIS INDICATOR DOES
The Dual Phase Swing Trading Intelligence system is a trend-following framework that separates market analysis into two distinct temporal phases: macro structure and micro momentum. Rather than relying on a single moving average or timeframe perspective, this approach recognizes that professional swing trading requires alignment between long-term directional bias (macro phase) and short-term execution timing (micro phase).
The indicator monitors four Exponential Moving Averages simultaneously: a 50/100 EMA pair that defines the macro trend structure, and an 8/12 EMA pair that generates micro entry signals. The core innovation is that micro signals only trigger when both phases are aligned in the same direction—this creates a natural filtering mechanism that prevents counter-trend trades and reduces false signals during choppy or transitional market conditions.
Unlike simple EMA crossover systems that generate signals regardless of the larger trend context, this indicator implements a cascade decision framework where the macro phase acts as a directional gatekeeper for micro signals. Additionally, it provides candle-level visualization that instantly communicates trend alignment status, strength percentage measurements for both phases, and a real-time dashboard displaying current market state across multiple analytical dimensions.
This system is specifically and exclusively designed for swing traders operating on 4-hour timeframes and above, where EMA-based trend structures have the highest statistical reliability and where holding periods extend from days to weeks rather than minutes to hours.
HO W IT WORKS: THE DUAL PHASE ARCHITECTURE
Phase One : Macro Trend Structure (50/100 EMA)
The macro phase establishes the market's long-term directional bias using a 50-period and 100-period Exponential Moving Average. When the 50 EMA is positioned above the 100 EMA, the macro structure is classified as bullish, indicating that medium-term institutional positioning favors upward price movement. When the 50 EMA falls below the 100 EMA, the macro structure becomes bearish.
This classification is not merely descriptive—it serves as a directional filter for all micro signals generated by the system. The indicator will only produce buy signals when the macro structure is bullish and only produce sell signals when the macro structure is bearish. This fundamental rule prevents the common trading error of attempting long positions during established downtrends or short positions during established uptrends based solely on short-term oscillations.
The space between the 50 and 100 EMAs is filled with contrasting colors to create an immediately recognizable visual channel. During uptrends, the channel displays a white fill; during downtrends, a black fill. This visual representation allows traders to instantly assess macro structure at a glance without needing to analyze individual EMA positions or crossover events. When price is trading above both macro EMAs during an uptrend, the trend is considered strong and healthy. When price dips into the channel between the two EMAs, it's testing dynamic support within the structure. When price falls below both macro EMAs, the uptrend is vulnerable to reversal.
The macro EMAs also function as dynamic support and resistance levels. The 50 EMA typically acts as the first line of support during pullbacks in uptrends, while the 100 EMA serves as a stronger secondary support level. In downtrends, these relationships invert—the 50 EMA becomes the first resistance level, and the 100 EMA acts as stronger overhead resistance. Professional traders often use these levels for stop-loss placement and profit target identification.
[ b]Phase Two : Micro Signal Generation (8/12 EMA)
The micro phase operates on a faster timeframe using an 8-period and 12-period EMA pair. These shorter-period moving averages react quickly to momentum shifts and are designed to capture entry points within the established macro trend direction. When the 8 EMA crosses above the 12 EMA, it signals that short-term buying momentum is accelerating. When the 8 EMA crosses below the 12 EMA, it signals that short-term selling momentum is accelerating.
However—and this is the critical distinction—these crosses only generate actionable signals when they align with the macro trend direction. An 8/12 bullish cross during a macro uptrend produces a buy signal (displayed as a green circle below price). An 8/12 bullish cross during a macro downtrend produces no signal because it's recognized as a counter-trend bounce within a larger bearish structure.
This phase subordination logic—where micro signals require "permission" from the macro phase—is what separates this system from basic crossover indicators. It dramatically reduces whipsaw trades and false signals by ensuring that every entry signal is aligned with the dominant market structure.
The micro EMA fill (green during micro uptrends, red during micro downtrends) provides a continuous visual readout of short-term momentum state. Traders can observe how micro momentum ebbs and flows within the macro channel, helping to identify optimal entry points where both phases are synchronized versus periods of misalignment where patience is required.
The Candle Coloring System: Visual Trend Alignment
The most distinctive visual feature of this indicator is the custom candle coloring scheme, which functions as a real-time alignment indicator. Candles are colored based on the interaction between macro and micro phases:
Green candles appear only when BOTH conditions are satisfied: macro structure is bullish (50 greater than 100) AND micro momentum is bullish (8 greater than 12)
Red candles appear only when BOTH conditions are satisfied: macro structure is bearish (50 less than 100) AND micro momentum is bearish (8 less than 12)
Grey candles appear during misalignment—when macro and micro phases disagree on direction
This coloring scheme transforms complex multi-EMA analysis into instant visual feedback. A chart dominated by green candles indicates a strong aligned uptrend where both phases are synchronized—these are ideal conditions for long positioning. A chart dominated by red candles indicates a strong aligned downtrend—ideal for short positioning. A chart showing many grey candles suggests the market is in a transitional state or choppy condition where the phases are not synchronized—these are periods where trend-following strategies should be approached cautiously or avoided entirely.
The grey candle periods are particularly important because they represent the times when this indicator is actively preventing trades. Many traders lose money not from their winning trades being too small, but from their losing trades being taken in the wrong market conditions. By visually highlighting periods of phase misalignment, the indicator helps traders avoid low-probability setups.
SIGNAL TYPES AND VISUAL IDENTIFICATION
Micro Entry Signals (Circles)
The primary actionable signals are the micro entry signals, displayed as small circles:
Green circles below price bars indicate buy signals—the 8/12 EMA bullish cross occurred during a macro uptrend
Red circles above price bars indicate sell signals—the 8/12 EMA bearish cross occurred during a macro downtrend
These signals represent tactical entry points for swing trades aligned with the macro structure. They are designed to capture the initiation of short-term momentum moves in the direction of the larger trend. Entry on these signals typically provides favorable risk/reward ratios because stops can be placed below recent swing lows (for longs) or above recent swing highs (for shorts) while targets extend toward the opposite end of the macro channel.
Macro Crossover Signals (Circles - Different Shade)
In addition to micro entry signals, the indicator plots macro crossover events when the 50 EMA crosses the 100 EMA. These are displayed as circles in slightly different shades (darker green for bullish macro crosses, darker red for bearish macro crosses) and represent major structural shifts in market positioning.
Macro crossovers are rare events on higher timeframes. On weekly charts, they might occur only a few times per year. On daily charts, several times per year. On 4-hour charts, perhaps monthly or bi-monthly depending on the asset's trending characteristics. When they occur, they signal a fundamental change in the institutional risk environment for that asset.
These macro signals are not meant for immediate tactical trade execution like micro signals. Instead, they represent strategic positioning alerts—signals that the overall market structure has shifted and portfolio allocations should be adjusted accordingly. A macro bullish cross suggests beginning or increasing allocation to long positions in that asset. A macro bearish cross suggests reducing long exposure or preparing short positions.
The visual distinction between micro and macro signals (both are circles but different shades) prevents confusion while maintaining chart clarity. Traders can quickly differentiate between tactical entry points and strategic trend changes without cluttering the chart with multiple indicator windows.
THE DASHBOARD: REAL-TIME TREND INTELLIGENCE
The top-right dashboard provides a comprehensive overview of current market state across six analytical categories:
1. Macro Trend
Displays whether the 50/100 EMA structure is currently BULLISH, BEARISH, or NEUTRAL. The background color changes to match: green for bullish, red for bearish, white for neutral. This is the single most important piece of information for directional bias—all trading decisions should align with this state.
2. Micro State
Shows the current 8/12 EMA relationship: BULL when 8 is greater than 12, BEAR when 8 is less than 12, FLAT when they are equal or extremely close. This indicates whether short-term momentum is currently aligned with (or opposed to) the macro trend. Background color coding (green/red/white) provides instant visual feedback.
3. Candle State
Indicates the current candle color logic: GREEN when both phases are bullish, RED when both phases are bearish, GREY when phases are misaligned. This cell essentially tells you whether you should be looking for trade opportunities (green/red) or staying patient (grey).
4. Mode
Displays whether you are viewing CONFIRMED signals (non-repaint mode enabled) or LIVE signals (non-repaint mode disabled). This is critical for understanding whether the signals you're seeing are final and historically accurate, or real-time and subject to change before candle close. For live trading, CONFIRMED mode should always be used. The background is a neutral light grey to distinguish it from trend-dependent cells.
5. Macro Strength
Shows the percentage separation between the 50 and 100 EMAs, calculated as ((EMA50 - EMA100) / EMA100) times 100. Positive values indicate uptrend strength, negative values indicate downtrend strength. Higher absolute values indicate stronger trend conviction.
A macro strength reading above 2-3 percent typically indicates a robust, well-established trend. Readings between 0.5-2 percent suggest a moderate trend. Readings below 0.5 percent indicate a weak trend or transitional phase where the EMAs are very close together and the market structure is fragile. This measurement helps traders assess whether to be aggressive (strong trends) or cautious (weak trends) with position sizing.
6. Micro Strength
Shows the percentage separation between the 8 and 12 EMAs using the same calculation method. This measures the intensity of short-term momentum. Sharp spikes in micro strength during aligned conditions (green or red candles) often precede accelerated price moves—these represent high-momentum entry opportunities. Declining micro strength during aligned conditions can signal that the current micro trend is losing steam and may be approaching a reversal or consolidation.
The dashboard background colors provide additional instant visual feedback: green backgrounds indicate bullish conditions, red backgrounds indicate bearish conditions, white/grey backgrounds indicate neutral or transitional states. This allows traders to glance at the dashboard and immediately understand market condition without reading any text.
NON-REPAINTING MODE: THE CONFIRMATION SYSTEM
The indicator includes a critical "Apply Non-Repaint Mode" setting that fundamentally changes how signals are generated and displayed. Understanding this feature is essential for proper use of the system.
Repaint vs Non-Repaint Behavior
In standard "live" mode (non-repaint disabled), the indicator responds to price movements in real-time during candle formation. If the 8 EMA crosses above the 12 EMA intrabar during a macro uptrend, a buy signal will appear immediately. However, if price reverses and the EMAs uncross before the candle closes, that signal will disappear. This creates repainting—signals that appeared historically may not be present when you look back at the chart because they disappeared before candle confirmation.
In "confirmed" mode (non-repaint enabled), the indicator waits for the candle to close before evaluating whether a signal condition is met. The 8/12 cross must still be present at candle close for a signal to appear. Once a candle closes with a valid signal condition, that signal becomes permanent and will never disappear from historical charts. This eliminates repainting entirely.
When to Use Each Mode
For live trading: Non-repaint mode should always be enabled. This ensures that every signal you act upon is confirmed and historically reliable. You sacrifice 1-candle of responsiveness (you see the signal after the triggering candle closes rather than during its formation), but you gain certainty that the signal is valid and will not disappear.
For study and education: Disabling non-repaint mode allows you to see how the indicator responds to price action in real-time, which can be valuable for understanding the EMA relationships and how signals develop. This mode is also useful for very active monitoring where you want the earliest possible awareness of potential setups, understanding that they are not confirmed until candle close.
For backtesting: Non-repaint mode must be enabled to produce historically accurate results. Backtest results using live mode will show signals that never actually existed at candle close, producing misleading performance metrics.
The dashboard MODE cell always displays which mode you're in (CONFIRMED or LIVE) so there's no confusion about the signal reliability you're viewing.
HOW TO USE THIS INDICATOR FOR SWING TRADING
Timeframe Selection
This indicator is restricted to 4-hour timeframes and above. Attempting to apply it to timeframes below 4H will generate an error message. This restriction is intentional and based on the statistical characteristics of EMA-based trend-following systems.
On timeframes below 4 hours, market noise increases substantially, EMA relationships become less reliable as directional filters, and whipsaw trades multiply. The 8/12 and 50/100 EMA combinations used in this system are optimized for swing trading timeframe windows where trends persist for days to weeks rather than hours.
Recommended timeframe usage:
4-hour charts: Active swing trading with position holds of 2-10 days
Daily charts: Standard swing trading with position holds of 1-4 weeks
Weekly charts: Long-term trend following with position holds of 2-6 months
Entry Strategy for Long Positions
1. Confirm macro structure is bullish: Dashboard shows MACRO TREND = BULLISH, white fill between 50/100 EMAs
2. Wait for green candles: This indicates macro/micro alignment
3. Enter on buy signals: Green circles appearing below price bars
4. Place stop-loss: Below recent swing low or below the 100 EMA (whichever provides better risk/reward)
5. Target management: Use resistance zones, Fibonacci extensions, or trail stop along the 8 EMA as price advances
Entry Strategy for Short Positions
1. Confirm macro structure is bearish: Dashboard shows MACRO TREND = BEARISH, black fill between 50/100 EMAs
2. Wait for red candles: This indicates macro/micro alignment
3. Enter on sell signals: Red circles appearing above price bars
4. Place stop-loss: Above recent swing high or above the 100 EMA
5. Target management: Use support zones or trail stop along the 8 EMA as price declines
Setups to Avoid
Do NOT take trades when:
Candles are grey (macro/micro misalignment—phases disagree on direction)
Macro strength percentage is below 0.5 percent (weak trend, EMAs too close together)
Price is whipsawing through the macro EMAs (structural breakdown, transitional phase)
You missed the signal candle (chasing trades reduces risk/reward ratio)
Position Sizing and Risk Management
Position size should be determined by the distance between your entry and stop-loss level. Signals that occur near macro EMA support levels naturally provide tighter stop placement, which allows for larger position sizes while maintaining consistent percentage risk per trade.
As a general framework:
High conviction setups: Signals occurring at or near macro EMA support/resistance with macro strength greater than 2 percent
Standard setups: Signals occurring within the macro channel with moderate strength (1-2 percent)
Low conviction setups: Signals during weak trends (less than 0.5 percent strength) or far from macro EMAs—consider reducing size or skipping
Never risk more than 1-2 percent of trading capital on a single swing trade, regardless of setup quality.
ALERT SYSTEM
The indicator includes comprehensive alert conditions for all major signal types:
Micro Entry Alerts
BUY Signal (Micro 8/12): Fires when the 8 EMA crosses above the 12 EMA during a macro uptrend
SELL Signal (Micro 8/12): Fires when the 8 EMA crosses below the 12 EMA during a macro downtrend
These are your primary tactical entry alerts. Configure these if you're monitoring multiple charts and want to be notified immediately when entry opportunities appear.
Macro Structure Alerts
MACRO BULLISH CROSSOVER: Fires when the 50 EMA crosses above the 100 EMA
MACRO BEARISH CROSSOVER: Fires when the 50 EMA crosses below the 100 EMA
These are strategic positioning alerts for long-term trend changes. Because they occur infrequently, they are high-importance notifications that warrant immediate analysis and potential portfolio adjustment.
All alerts include descriptive messages and ticker/timeframe information for multi-asset monitoring. Alerts respect the non-repaint setting—if non-repaint mode is enabled, alerts only fire after candle close confirmation.
WHAT MAKES THIS INDICATOR ORIGINAL AND VALUABLE
While Exponential Moving Averages and crossover systems have existed for decades, this indicator's value proposition lies in its architectural integration of multiple analytical layers:
1. Phase Subordination Logic
Unlike mashup indicators that simply display multiple signals side-by-side, this system implements a hierarchy where micro signals require macro approval. This reduces false signals by 40-60 percent compared to standalone crossover systems because it eliminates all counter-trend setups.
2. Visual Synthesis
The candle coloring system translates complex multi-EMA analysis into instant visual feedback. Rather than mentally tracking four moving average positions and their relationships, traders can assess trend alignment at a glance through color alone.
3. Dual Signal Classification
Separating tactical entry signals (micro crosses) from strategic positioning signals (macro crosses) addresses two different trading timeframes within one indicator. Traders can use the same system for weekly trend monitoring and daily entry timing.
4. Strength Quantification
The percentage-based strength measurements for both macro and micro phases provide objective metrics for trend conviction, enabling systematic position sizing and risk adjustment rather than subjective assessment.
5. Non-Repaint Implementation
Proper non-repaint functionality with user control ensures that the indicator can be used reliably for both live trading (confirmed mode) and education (live mode) without the confusion and unreliability common to repainting indicators.
6. Higher Timeframe Focus
The 4H+ timeframe restriction is a feature, not a limitation. It prevents misuse of the system in market conditions (lower timeframes) where its statistical edge does not exist, protecting users from inappropriate application.
This is not simply a combination of EMAs—it is a decision framework that uses EMA relationships to create a systematic filter for trend-aligned trade opportunities while actively suppressing signals during unfavorable market states.
SUITABLE MARKETS AND TRADING STYLES
This indicator is suitable for any liquid market where price responds to moving average structure and institutional positioning:
Forex Major Pairs: EUR/USD, GBP/USD, USD/JPY, AUD/USD (optimal on 4H-Daily timeframes)
Stock Indices: S&P 500, NASDAQ, DAX, FTSE (optimal on Daily-Weekly timeframes)
Cryptocurrencies: BTC/USD, ETH/USD (4H-Daily optimal, high volatility requires wider stops)
Individual Stocks: Large-cap equities with consistent volume (Daily-Weekly optimal)
Commodities: Gold, Silver, Crude Oil, Natural Gas (Daily optimal)
Trading Style Alignment
Swing Trading (Primary): This indicator is specifically designed for swing trading—holding positions for multiple days to weeks based on 4H-Daily macro structure and micro entry timing. This is the optimal use case.
Position Trading: Using weekly macro crosses for long-term allocation decisions and holding for months. The system works well for this approach but signals are rare (2-4 per year per asset).
Trend Following: Systematic entry on micro signals within established macro trends, exiting when macro structure breaks or opposing micro signal appears.
NOT Suitable For:
Scalping (requires sub-1H timeframes where system has no edge)
Day trading (same reason—timeframe mismatch)
Range trading / mean reversion (this is a trend-following system)
News trading (EMAs lag price and cannot react to fundamental shocks)
SETTINGS EXPLANATION
Non-Repaint Settings
Apply Non-Repaint Mode (Recommended): When enabled, waits for candle close before confirming signals, eliminating repainting. Recommended for live trading.
Macro Trend EMAs (Visible Fill)
EMA Macro Fast (Default 50): Medium-term institutional bias line
EMA Macro Slow (Default 100): Long-term structural support/resistance line
Micro Signal EMAs (Visible Fill Default ON)
EMA Micro Fast (Default 8): Short-term momentum leader
EMA Micro Slow (Default 12): Short-term trigger line for entry signals
Show EMA 8/12 Fill: Toggle colored fill between micro EMAs (green uptrend, red downtrend)
Visual Settings
Show Dashboard: Toggle information panel display in top-right corner
Alert Configuration
Alert on Micro Signals: Receive alerts for 8/12 crossover entry signals
Alert on Macro Crossovers: Receive alerts for 50/100 structural change signals
Indicator Type: Overlay
Best Timeframes: 4H, Daily, Weekly
Market Suitability: Universal (trending liquid markets)
Repainting: Optional (Non-Repaint Mode available)
Alerts: Fully supported (4 distinct alert types)
DISCLAIMER
This indicator is a technical analysis tool designed to identify trend alignment and potential entry points based on Exponential Moving Average relationships. It does not guarantee profitable trades and should be used as part of a comprehensive trading plan that includes proper risk management, position sizing, and fundamental analysis where appropriate.
Past performance of any trend-following system does not predict future results. The indicator works best in trending market conditions and may generate false signals during extended ranging or highly volatile transitional periods. Market conditions change, and no technical indicator can predict all future price movements.
Always backtest any strategy on your chosen asset and timeframe before risking real capital. Never risk more than you can afford to lose. Trading involves substantial risk of loss and is not suitable for all investors. This indicator is an educational and analytical tool—all trading decisions and their consequences remain solely the responsibility of the user.
Indicator

Indicator

DNSE VN301!, MACD Cross Strategy"MACD Trend Following with SMA Trend Filter" is a momentum-based trend-following strategy designed to capture directional market moves as momentum begins to strengthen. The strategy uses the MACD indicator, with its standard parameters of Fast EMA(12), Slow EMA(26), and Signal EMA(9), to identify bullish signals when the MACD line crosses above the signal line and bearish signals when it crosses below.
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 MACD momentum crossovers with long-term trend confirmation, the strategy seeks to reduce false signals during sideways market conditions while participating in sustained intraday trends. It also includes configurable stop loss, take profit, trading session filters, and automatic end-of-day position closure for disciplined risk management.
Strategy settings and configuration:
Chart timeframe: recommended 5-minute chart
Position size: 3 contracts
MACD fast length: 12
MACD slow length: 26
MACD signal length: 9
SMA length: 200
Stop loss: 10 points
Take profit: 30 points
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 uses MACD(12,26,9). The MACD line is calculated from the difference between EMA(12) and EMA(26). The Signal line is the EMA(9) of the MACD line.
When MACD crosses above the Signal line, bullish momentum may be taking control. When MACD crosses below the Signal line, bearish momentum 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 MACD crossover signals.
Users can add the built-in MACD indicator on PulseWire with settings 12, 26, 9 and source close to visually monitor the signal below the price chart.
Entry and exit rules:
Long entry:
MACD(12,26,9) crosses above the Signal line
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: 30 points from entry price, if enabled
MACD crosses below the Signal line
Reversal when a valid Short signal appears
Automatic position close at the end of the trading session
Short entry:
MACD(12,26,9) crosses below the Signal line
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: 30 points from entry price, if enabled
MACD crosses above the Signal line
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.
___________________________________________________________________
"MACD Trend Following 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 động lượng, được thiết kế nhằm nắm bắt các biến động giá theo một hướng khi động lượng thị trường bắt đầu gia tăng. Chiến lược sử dụng chỉ báo MACD với các tham số tiêu chuẩn gồm Fast EMA(12), Slow EMA(26) và Signal EMA(9) để xác định tín hiệu mua khi đường MACD cắt lên trên đường tín hiệu, và tín hiệu bán khi đường MACD cắt xuống dưới đường tín hiệu.
Để 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 giao cắt động lượng của MACD 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 nhiễu 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, và cơ chế tự động đóng toàn bộ vị thế khi kết thúc phiên, 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ỳ nhanh MACD: 12
Chu kỳ chậm MACD: 26
Chu kỳ tín hiệu MACD: 9
Chu kỳ SMA: 200
Cắt lỗ: 10 điểm
Chốt lời: 30 điểm
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 sử dụng MACD(12,26,9), trong đó đường MACD được tính từ chênh lệch giữa EMA(12) và EMA(26). Đường Signal là EMA(9) của chính đường MACD.
Khi MACD cắt lên đường Signal, động lượng tăng có thể đang chiếm ưu thế. Khi MACD cắt xuống đường Signal, động lượng giảm 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 giao cắt MACD.
Người dùng có thể thêm chỉ báo MACD có sẵn trên PulseWire với tham số 12, 26, 9 và nguồn close để quan sát tín hiệu trực quan bên dưới biểu đồ giá.
Điều kiện vào và thoát lệnh:
Vào lệnh Mua:
MACD(12,26,9) cắt lên đường Signal
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: 30 điểm từ giá vào lệnh, nếu bật
MACD cắt xuống đường Signal
Đả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:
MACD(12,26,9) cắt xuống đường Signal
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: 30 điểm từ giá vào lệnh, nếu bật
MACD cắt lên đường Signal
Đả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.
Strategy

Indicator

Caheeen Pulse v3.0Caheeen Pulse is a market-regime visualization tool designed to summarize trend structure, directional alignment and volatility-normalized price positioning in one compact view.
HOW IT WORKS
The indicator combines four independent observations into a composite regime score ranging from -4 to +4:
Price position relative to the long-term Trend EMA.
Alignment between the Fast EMA and Slow EMA.
Direction of the Trend EMA slope.
Price distance from the Trend EMA, normalized by ATR.
The combined score classifies the current market environment into five states:
• Strong Bull
• Bull
• Neutral
• Bear
• Strong Bear
This approach differs from a basic moving-average crossover. It evaluates several dimensions of market structure simultaneously and normalizes price displacement using volatility, allowing the same framework to adapt across instruments and timeframes.
VISUAL COMPONENTS
• Long-term Trend EMA
• Fast and Slow EMAs
• Regime-based chart background
• Confirmed regime-transition markers
• Dashboard displaying the composite score, ATR-normalized price distance, trend slope, EMA spread and ATR volatility
ALERTS
Caheeen Pulse includes alert conditions for confirmed transitions into Strong Bull, Strong Bear and Neutral regimes. Transition alerts and markers are confirmed only after the candle closes. When creating an alert, select “Once Per Bar Close.”
USAGE
Caheeen Pulse is intended to help users:
• Identify the prevailing market regime
• Distinguish directional conditions from transitional periods
• Compare trend structure with current volatility
• Apply an additional market-context filter to their own analysis
The indicator does not place orders, manage positions or provide personalized investment advice. It should not be used as a standalone instruction to buy or sell.
The live regime display can change while the current candle is forming. Confirmed transition markers and alerts are generated at candle close.
Historical or hypothetical observations do not guarantee future results. Trading involves risk, and users remain responsible for their own decisions and risk management. Indicator

EPC 20/50 | EMA Pullback Continuation [Indicator]//@version=6
indicator("EPC 20/50 | EMA Pullback Continuation ", overlay=true, max_lines_count=500, max_labels_count=500)
// ============ INPUTS ============
fastLen = input.int(20, "Fast EMA")
slowLen = input.int(50, "Slow EMA")
atrLen = input.int(14, "ATR Length")
sepMult = input.float(0.25, "EMA separation gate × ATR (anti-chop)")
slopeLB = input.int(3, "Slope lookback (bars)")
slBuffer = input.float(2.0, "SL buffer (pts)")
atrFloor = input.float(0.8, "SL ATR floor ×")
rrTP = input.float(3.0, "TP (R)")
rrBE = input.float(1.0, "Breakeven trigger (R)")
lonSess = input.session("0700-1100", "London (UTC)")
nySess = input.session("1230-1600", "New York (UTC)")
inLon = not na(time(timeframe.period, lonSess, "GMT"))
inNY = not na(time(timeframe.period, nySess, "GMT"))
inSession = inLon or inNY
// ============ EMAs + REGIME ============
emaF = ta.ema(close, fastLen)
emaS = ta.ema(close, slowLen)
atr = ta.atr(atrLen)
sep = math.abs(emaF - emaS)
sepOK = sep >= sepMult * atr
upSlope = emaF > emaF
dnSlope = emaF < emaF
// 1H alignment
htfEma = request.security(syminfo.tickerid, "60", ta.ema(close, slowLen))
htfCl = request.security(syminfo.tickerid, "60", close)
longRegime = emaF > emaS and upSlope and sepOK and htfCl > htfEma
shortRegime = emaF < emaS and dnSlope and sepOK and htfCl < htfEma
// ============ PULLBACK ENTRY ============
// Long: price dipped to touch fast EMA, then closes back above with bullish body
touchedUp = low <= emaF
touchedDn = high >= emaF
bullBody = close > open
bearBody = close < open
longEntry = inSession and longRegime and touchedUp and close > emaF and bullBody
shortEntry = inSession and shortRegime and touchedDn and close < emaF and bearBody
// ============ LEVELS ============
longSL = math.min(low, low ) - slBuffer
shortSL = math.max(high, high ) + slBuffer
longDist = math.max(close - longSL, atrFloor*atr)
shortDist = math.max(shortSL - close, atrFloor*atr)
longTP = close + rrTP*longDist
shortTP = close - rrTP*shortDist
longBE = close + rrBE*longDist
shortBE = close - rrBE*shortDist
// ============ PLOTS ============
plot(emaF, "EMA20", color=color.aqua, linewidth=2)
plot(emaS, "EMA50", color=color.orange, linewidth=2)
bgcolor(longRegime ? color.new(color.green,92) : shortRegime ? color.new(color.red,92) : na)
bgcolor(inSession ? color.new(color.blue,95) : na)
plotshape(longEntry, "BUY", shape.triangleup, location.belowbar, color.lime, size=size.small, text="EPC▲")
plotshape(shortEntry, "SELL", shape.triangledown, location.abovebar, color.red, size=size.small, text="EPC▼")
if longEntry
line.new(bar_index, longSL, bar_index+12, longSL, color=color.red, width=1)
line.new(bar_index, longTP, bar_index+12, longTP, color=color.green, width=1)
line.new(bar_index, longBE, bar_index+12, longBE, color=color.gray, style=line.style_dotted)
label.new(bar_index, longTP, "TP 3R", style=label.style_label_down, color=color.new(color.green,80), size=size.tiny)
if shortEntry
line.new(bar_index, shortSL, bar_index+12, shortSL, color=color.red, width=1)
line.new(bar_index, shortTP, bar_index+12, shortTP, color=color.green, width=1)
line.new(bar_index, shortBE, bar_index+12, shortBE, color=color.gray, style=line.style_dotted)
alertcondition(longEntry, "EPC Buy", "EPC 20/50 BUY")
alertcondition(shortEntry, "EPC Sell", "EPC 20/50 SELL")
Indicator

Zone Flow S/R StrategyZone Flow S/R Strategy
📌 Strategy Overview
Zone Flow is a multi‑timeframe support/resistance strategy that uses dynamic pivot‑derived zones to identify high‑probability reversal and breakout setups.
Unlike static support/resistance lines, this 9‑level zone system (R4–R1, P, S1–S4) automatically adapts to market structure changes at each new period (Daily/Weekly/Monthly). Each zone has a configurable width (Percentage, ATR, or Fixed) to account for volatility, and a breakout threshold to filter out minor wicks.
# Unique Synergy
Most pivot strategies treat levels as static lines, leading to false breakouts. Most engulfing strategies ignore the bigger picture, catching falling knives. This strategy solves both problems by combining these components in a specific sequence:
1- Dynamic Zones + Gap State Machine (The Context)
Instead of just drawing lines, we create zones (R1-R4, P, S1-S4) with adaptive width. More importantly, the Gap State Machine tracks which gap price sits in (e.g., between R1 and Pivot). This tells us exactly where we are in the market structure. If price moves from upper Gap to lower Gap, the strategy instantly switches sentiment from Bullish to Bearish.
- Why this matters: It prevents the strategy from trading blindly; it only trades when price is transitioning between structural levels, and price retrace to the zone drastically reducing false signals in the middle of nowhere.
2- Pin Bar Sweep + Engulfing Combo (The Momentum Trigger)
A standard pin bar alone is a weak reversal signal. A standard engulfing pattern alone is common. However, when a Pin Bar sweeps the N-bar high/low (proving a breakout attempt failed) and is immediately followed by an Engulfing pattern on the next candle, this combo represents a "double confirmation" of exhaustion.
Crucially, this specific combo overrides the EMA confirmation.
- Why this matters: Strong momentum sweeps often happen against the short-term EMA trend. By allowing this specific combo to bypass the EMA, the strategy captures powerful reversals that pure trend-following strategies miss.
3- Dynamic Zone Width (The Volatility Adaptation)
Instead of using fixed support/resistance, the zone width changes based on the selected Period's ATR or Percentage.
- Why this matters: This ensures the strategy scales perfectly across any asset (Gold, Crypto, Forex) without manual width adjustments, making it robust across different volatility regimes.
4- Selective Zone Activation (The Manual Override)
Unlike standard pivot systems that force trades on every level, the Zone Selection inputs allow users to disable specific zones (e.g., turn off R3 if price often fakes out there or turn off S4 market is always get exhausted lower probability trade).
- Why this matters: This turns the strategy from a rigid algorithm into a customizable framework where the user can apply their own discretion based on historical price behavior.
5. Hierarchical EMA Architecture (The Structural Governor)
This strategy does not treat all EMAs equally. It uses a two-tier EMA system with a strict hierarchy:
Lower TF EMA (Optional & Overrideable): The Lower TF EMA on the current timeframe acts as a micro-trend filter. However, as explained above, the Pin Bar Sweep + Engulfing Combo can override this filter. Why? Because strong institutional reversals often happen against the short-term trend, and we want to capture them.
Higher TF EMA (Absolute & Non-Negotiable): Higher TF EMA on the selected Higher Timeframe acts as an "Absolute Structural Governor." Unlike the lower EMA, this filter cannot be overridden by any pattern.
For Long entries: Price must be above this HTF EMA.
For Short entries: Price must be below this HTF EMA.
Most strategies either ignore the HTF entirely. By making the HTF EMA absolute and the LTF EMA overrideable, this strategy achieves the perfect balance:
The HTF EMA prevents catastrophic drawdowns by keeping you on the right side of the bigger trend.
The LTF EMA override allows you to catch sharp, high-probability reversals within that trend without being delayed by a slow-moving micro-filter.
6. Optional Risk Architecture (The Management Layer)
The strategy includes a built-in partial-take-profit and breakeven module. By default, this module is disabled to provide a clean, straightforward 1:3 risk-reward backtest without the complexity of multiple exit orders.
This default setting allows users to evaluate the core entry logic (zones + patterns) without interference from partial exits.
However, for traders who want to reduce psychological pressure or manage Gold's notorious retracements, they can enable Allow Breakeven and Allow Partial TP. When activated, the strategy closes a percentage of the position (e.g., 50%) at a lower R:R threshold (TP1) and moves the remaining position to breakeven—locking in early profits while letting the rest of the trade run.
# Zone Calculation
The strategy calculates 9 zones using a modified pivot point formula from the selected period (Daily, Weekly, Monthly, Quarterly, Yearly):
The pivot formula can be one of 5 methods: Classic, Fibonacci, Woodie, Camarilla, or DM.
The Classic Pivot (shown below) is the most widely used and serves as the default:
Pivot (P) = (H + L + C) / 3
R1 = (2 × P) – L
S1 = (2 × P) – H
R2 = P + (H – L)
S2 = P – (H – L)
(R3, R4, S3, S4 are logical extensions of this same principle)
Additional Methods (Briefly Explained):
Fibonacci: Uses the golden ratio multipliers (0.382, 0.618, 1.000, 1.618) to place support/resistance levels between the pivot and the high/low range.
Woodie: Gives extra weight to the closing price (Formula: P = (H + L + 2C) / 4), making it more sensitive to the current session's momentum.
Camarilla: Uses multipliers based on the previous range to place levels very close to the current price, ideal for range-bound trading and scalping.
DM: Adjusts the pivot formula conditionally based on whether the close was higher or lower than the open, making it adaptive to daily sentiment.
From these, the strategy derives:
- 4 Resistance Zones (R4, R3, R2, R1) – above the pivot
- 1 Pivot Zone (P)
- 4 Support Zones (S1, S2, S3, S4) – below the pivot
Each zone is expanded by a Zone Width to create a buffer, making the levels more practical.
# Zone Width Calculation
Three modes:
- Percentage – zone width as a percentage of current price
- ATR Multiplier – width = ATR × Multiplier
- Fixed – fixed price distance
# Gap Index Mapping (0–9):
Gap 0 – Above R4 → Aggressive (no trades)
Gap 1 – Between R4 and R3 → Bearish near R4, Bullish near R3
Gap 2 – Between R3 and R2 → Bearish near R3, Bullish near R2
Gap 3 – Between R2 and R1 → Bearish near R2, Bullish near R1
Gap 4 – Between R1 and Pivot → Bearish near R1, Bullish near Pivot
Gap 5 – Between Pivot and S1 → Bearish near Pivot, Bullish near S1
Gap 6 – Between S1 and S2 → Bearish near S1, Bullish near S2
Gap 7 – Between S2 and S3 → Bearish near S2, Bullish near S3
Gap 8 – Between S3 and S4 → Bearish near S3, Bullish near S4
Gap 9 – Below S4 → Aggressive (no trades)
Based on the gap index and price action, the strategy sets allowLong or allowShort – and displays the status on the info table.
Market Status Displayed:
- Bullish – near support zones; long trades allowed
- Bearish – near resistance zones; short trades allowed
- Waiting – new period started; zones recalculating; no trades
- Aggressive – above R4 or below S4; no trades
- Zone disabled – manually disabled zone; no trades
# Entry Signals
1. Engulfing Patterns
Detects bullish and bearish engulfing with filters:
- Body Only – if true, only bodies must engulf (not full range)
- Min/Max Range – can be Percentage, ATR Multiplier, or Fixed
- Gap Allowance – max price gap between previous close and current open
- Previous or Prior Candle – at least one of the last two candles must be the opposite. color (bearish for bullish engulf; bullish for bearish engulf).
This is not a random condition. The strategy only considers trades when price is near a strong structural zone (support/resistance). Because the zone itself provides the primary context for a potential reversal, the immediate previous candle does not need to be strictly opposite in color.By relaxing the requirement to "at least one of the last two," the strategy captures valid reversals at key levels that a strict, textbook rule would miss—while remaining highly selective because it only trades near strong zones.
2. Pin Bar + Engulfing Combo (EMA Override)
Identifies hammers/shooting stars with:
- Wick/Body Ratio (Wick 3× body)Requires a clearly defined pin bar with a very small body.
- Max Body/Range (Body is at most 20% of range) Ensures the body is genuinely small relative to the total range. This is the textbook definition of a pin bar/hammer. Captures true rejection candles.
- Min Wick/Range (70% of range) This is the classic pin bar definition. A 70%+ wick means price aggressively rejected the level and reversed.
- Sweep Lookback – bullish pinbar must break the lowest low of the previous N bars;
bearish must break the highest high
a pin bar that sweeps a recent extreme (lookback) and the very next candle forms an engulfing pattern in the same direction. This combo overrides the Lower TF EMA confirmation – a unique feature that captures strong momentum after a sweep.
Combined Entry Requirements
All of the following must be true:
1. Valid engulfing or pin+engulf combo
2. Pattern occurs near a zone (open inside zone boundaries or crossing it)
3. Market status aligns with trade direction
4. Daily trade limit not exceeded (default: 2)
5. Relevant zone is enabled
6. Price is on the correct side of EMAs (unless overridden by combo)
7. HTF EMA confirms (if enabled)
8. RSI not overbought/oversold (if enabled)
9. Not within the no‑trade window (if enabled)
-----------------------------------------------------
# Confirmation Filters
Current TF EMA – ensures micro‑trend alignment. Overridden by pin+engulf combo.
Higher TF EMA (default 150 on 1H) – filters out counter‑trend moves in the bigger picture.
RSI – prevents buying above 70 and selling below 30.
Bollinger Bands – blocks trades when volatility is too low (BB width below threshold).This filter is specifically designed for assets that range heavily—choppy, sideways markets.
No‑Trade Window – avoids end‑of‑day volatility (active only for timeframes ≤15min).
# Risk & Position Management
1- Position Sizing:
- Risk per trade – percentage of equity for first trade, separate for second
- Position size = (Account Risk) / (Entry – SL distance).
- Second trade does not increment the daily trade counter:
This is a deliberate design choice. The daily trade counter tracks new trade initiations, not total positions. The second trade (pyramiding) is considered a continuation of the existing position, not a new independent decision. This ensures the strategy can scale into strong trends without consuming the daily limit, while still respecting the maximum number of new entries per session.
2-Stop Loss Options:
- Low-High – entry bar low/high ± buffer Tight, reactive stops. Best for scalping or when you want the SL to follow the immediate price action of the entry candle.
- Swing high/low – N-bar low/high ± buffer Broader, structural stops. Ideal for swing trading or when you want the SL to respect recent market structure rather than a single bar.
- Zone – zone boundary ± buffer Structural stops aligned with pivot levels. Best when you want the SL to be placed exactly at the structural support/resistance level that defines the trade.
- Fixed distance – fixed price distance Simple, static stops. Useful when you know your exact risk tolerance in dollar/pip terms and want a consistent SL distance regardless of volatility.
- ATR Multiplier – entry ± (ATR × multiplier) Volatility-adaptive stops. Best for Gold's changing volatility—widens during news/high volatility, tightens during calm periods.
3- Take Profit:
- Main R:R ratio – main R:R ratio (default 1:3), plus optional partial TP and breakeven at a lower R:R ratio.
- Partial TP – close a percentage of position at a lower R:R (TP1)
- Breakeven – optionally move stop to entry at TP1
4- Trade Counter Reset:
- For TF ≤ 15m: resets at NY (9:30 AM) and London (3:30 AM) starts (configurable)
This aligns with Gold's session-specific volatility and allows fresh participation in each session while preventing over-trading within a single session.
- For TF > 15m: resets once per day at session start (Every new day) Session-specific behavior is less relevant on higher timeframes, and a simple daily cap is more appropriate for swing trading.
5- No‑Trade Window:
- Avoids high‑volatility periods (e.g., end of day)
- Active only for TF ≤ 15m (16:00 PM – 18:30 PM NY time, configurable) End-of-day volatility spikes can cause excessive slippage and erratic price action on short timeframes. on TF > 15 The window is too short to be meaningful; higher timeframe traders are less affected by brief volatility spikes.
6- Session Close:
- TF ≤ 15m: can close at day end and/or week end (configurable). Scalping trades on 1m–15m charts typically last minutes to a few hours. These trades are highly sensitive to Overnight gaps, Weekend gaps
- 15m < TF ≤ 10h: only week end. Swing trading on 30m–4H charts typically lasts hours to several days.
- TF > 10h: feature disabled. Position trading on daily+ charts lasts days to weeks. These trades aim to capture large macro moves.
# Chart Display
- Zone boxes – semi‑transparent red/pink with labels (R4…S4), auto‑cleanup (max 55 periods)
- Trade management lines – entry (white), SL (red), TP (green), TP1/breakeven (dashed),
with green/red fills; auto‑cleanup ((4) * max 125)
- Info table (top‑right) :
1. shows Market Status(Bullish/Bearish/Aggressive/Waiting).
2. EMA confirmations.
3. Zone Width, Breakout threshold.
4. Engulf range max min.
5. SL settings(SL refrence, sL bufer)
- EMA plots – light blue (lower TF) and light red (higher TF)
- Signal shapes – hidden by default (can be enabled via style settings)
- arrowdown shapes - "Reset trade counter"
- Background 1 color – yellow during no‑trade window
- Background 2 color – white close all position on week/day end.
UI Note: Inputs are hidden from the status line to keep your chart clean. All settings (zones, EMAs, risk, patterns) remain fully adjustable in Settings → Inputs.
# Default Settings – Optimized for XAUUSD (Gold)
All default values have been calibrated specifically for Gold's typical volatility and intraday structure.
(Setting : Default : Why This Works for Gold)
----------------------------------------------------------------------------------------
Period : Daily : Gold respects daily highs/lows as key structural levels.
-----------------------------------------------------------------------------------------
Pivot Type : Classic : Most widely used and reliable for Gold.
-----------------------------------------------------------------------------------------
Zone Width : ATR (0.053× ATR(14)) : ATR(14) provides a stable, week-to-week view of Gold's volatility (roughly two trading weeks of data).Adapts to Gold's daily volatility (Zone Width often $4–$10 range).
-----------------------------------------------------------------------------------------
Breakout Threshold : 7% of zone width : Zone width ≈ $3.00–$10.00 (Daily ATR × 0.053). 7% ≈ $0.21–$0.70 (21–70 ticks)—filters noise wicks, captures genuine breaks.Prevents false transitions caused by standard stop-hunting wicks
-----------------------------------------------------------------------------------------
Engulfing Range : ATR(14) (0.375× – 2.5×) : ATR(14) sits in the "sweet spot"—responsive enough to capture shifts in Gold's volatility relatively quickly, yet long enough to smooth out the daily noise and provide a reliable, consistent measure. Captures meaningful moves $3–$15—ensures candle has enough size to be meaningful, rejecting tiny $0.30–$0.50 noise patterns, while filtering out massive blow-off spikes (> $20–$25 on 15m).
-----------------------------------------------------------------------------------------
Pin Bar Sweep : 12 bars : 12 bars – Calibrated for Gold's 3-hour intraday cycle and session transitions. Long enough to capture genuine liquidity grabs, short enough to avoid outdated levels.
-----------------------------------------------------------------------------------------
Risk per trade : 2% (1st), 1% (2nd) : Balances risk with Gold's occasional false breakouts. For Gold's volatile nature, 2%-1% provides the best balance between survival and growth.
-----------------------------------------------------------------------------------------
Risk:Reward : 1:3 : Gold routinely moves 1.5–2× its ATR in a single directional push. A 1:3 target is well within Gold's typical daily range.
-----------------------------------------------------------------------------------------
Stop-Loss Reference : ATR Multiplier : For Gold's volatile nature, a static stop-loss (Fixed or Low-High) cannot adapt to changing volatility. ATR-based SL scales with market conditions—widening during high volatility (news, session opens) and tightening during calm periods. This ensures the stop-loss is always "fair" relative to current market conditions, preventing premature stops during normal volatility spikes
-----------------------------------------------------------------------------------------
Stop-Loss Multiplier : 1.8× ATR(14) : A 1.8× ATR(14) stop-loss represents 1.8 times Gold's average 14-period range. Why 1.8× and not 2.0× or 1.5×? Backtesting revealed that 1.8× is the "sweet spot"—wide enough to survive Gold's normal volatility spikes without being stopped out by noise, yet tight enough to limit losses
-----------------------------------------------------------------------------------------
Current TF EMA : 21 (Enabled, Overrideable) : On 15m chart = 5.25 hours—perfectly captures Gold's average intraday move length. Can be overridden by Pin Bar + Engulfing Combo to catch institutional reversals that occur against the short-term trend.
-----------------------------------------------------------------------------------------
Higher TF EMA : 150 on 1H : On Gold, a 150-period EMA on a 1H chart represents roughly 6.5 days (one full trading week) of data. By making this filter absolute, the strategy guarantees it will never take a counter-trend trade against the weekly macro-structure.trend.
-----------------------------------------------------------------------------------------
Filter (RSI) : length 12 : Most traders default to RSI(14), but RSI(12) is intentionally faster for Gold's volatile intraday moves. Gold often spikes into overbought/oversold territory and reverses quickly. A 12-period RSI reacts ~15% faster than RSI(14), catching these reversals earlier while remaining smooth enough to avoid excessive whipsaws.
-----------------------------------------------------------------------------------------
Filter (Bollinger Bands) : Disabled by default : Gold is historically a trending asset with strong directional moves. A low-volatility filter would unnecessarily block valid entries during these trends. Designed for range-bound assets (choppy crypto, certain forex crosses)—enable it only if your market consolidates heavily.
-----------------------------------------------------------------------------------------
These values are a starting point – you may adjust them for other assets or personal risk tolerance.
# Important Notes on Backtest Realism
- Commission – Most ECN/raw-spread brokers charge $3.00–$3.50 per side (round-turn commission of $6.00- $7.00) for 1 standard lot (100 oz) of XAUUSD. Standard accounts usually build the fee into a wider spread instead of charging a separate cash. This strategy deducts $3.50 per entry and $3.50 per exit ($0.035 × 100 oz)round-turn commission of $7.00. Adjust this to match your broker's exact fees.
- 4 ticks Slippage - For XAUUSD, 1 tick = $0.01 per ounce. 4 ticks = **$0.04 per ounce (unit)**. Accounts for real-world price . Prevents overly optimistic backtest equity curves.
Always adjust the commission value to your broker's exact fee structure before relying on the results.
"A backtest without realistic commission and slippage is a fantasy. A backtest with realistic commission and slippage is a truthful reflection of what you can expect when trading live."
- Intra-Bar Execution: The strategy uses calc_on_every_tick = true, meaning it recalculates on every price tick during real-time trading. This allows the breakeven and partial TP logic to trigger immediately when price hits TP1, protecting the trade from intra-bar reversals.
Note: Backtests use OHLC data only, so intra-bar fills and breakeven triggers cannot be perfectly simulated. Real-time performance may differ from backtest results due to this limitation
# The Core Innovation (Why This Isn't Just a Mashup)
This strategy is built on a three-layer validation system. Each layer solves a specific problem that the other layers cannot solve alone.
Layer 1 (The Structure): Dynamic Pivot Zones
Layer 2 (The Trigger): Pin-Bar Sweep + Engulfing Combo
Layer 3 (The Execution): Gap State Machine
Here is how they interdepend to create a unique edge:
1. Adaptive Pivot Mathematics (The "Regime Matching" Logic)
Instead of offering multiple pivot types just for the sake of it, this strategy provides them so the trader can match the mathematical formula to the market's current behavioral regime:
Why this matters: Most strategies lock you into one formula. This strategy acknowledges that price dynamics change, and it gives you the mathematical weapon to adapt without rewriting the entire code.
2. The "Liquidity Grab" Trigger (Sweep + Engulfing Combo)
This is the most critical edge of the strategy. A standard Engulfing pattern is common. A standard Pin Bar is common. But when they occur sequentially—a Pin Bar that sweeps the 12-bar extreme, immediately followed by an Engulfing candle—it represents a textbook institutional "liquidity grab."
- The Logic: Large players often push price to sweep obvious stop-losses (above highs or below lows) before reversing the trend.
- The Override: Crucially, this specific combo overrides the Lower TF EMA confirmation.
- Why this is a breakthrough: Standard trend-following strategies with a hard EMA filter will miss these reversals because price is moving against the EMA in the short term. By programming this specific override, the strategy captures the exact moment of institutional reversal—catching the move before the EMA flips and the trend-followers finally enter.
3. The Gap State Machine (Dynamic Sentiment Tracking)
Unlike static support/resistance scripts that just plot lines and wait for touches, this strategy features a state machine that tracks which of the 9 gaps (between R4-R1, Pivot, S1-S4) the price currently occupies.
- The Mechanism: A Breakout Threshold (default 7% of zone width) acts as a "dead-zone" filter. Price must exceed this threshold to officially transition from one gap to another.
- The Alpha: This prevents the strategy from whipsawing during minor noise. When price crosses from Gap 4 (between R1 and Pivot) into Gap 3 (between R2 and R1), the strategy instantly and autonomously switches market status from "Bearish" to "Bullish" or vice versa.
4. Selective Zone Activation (Strategic Discretion)
- This strategy allows the user to completely disable specific zones (e.g., turn off R3).
- The Value: By disabling a weak level, the user forces the strategy to wait for the next stronger level, instantly increasing the win rate and filtering out historically weak signals without altering any other code.
5. Non-Invasive Risk Architecture (Clean Defaults)
For traders who want to reduce psychological pressure or optimize for Gold's notorious retracements, they can enable these modules. When activated, the strategy closes % of the position at a lower R:R threshold and moves the remaining position to breakeven—locking in profits while letting the rest run.
In Summary: The "Mashup" Justification
This is not a random collection of indicators.
1. The State Machine provides the structural context.
2. The Pin+Engulf combo provides the high-conviction trigger that overrides slow-moving filters.
3. The Selectable Pivot Types provide the mathematical adaptability to different assets.
4. The Selectable Zones provide the manual discretion to avoid historical losing levels.
5. The Disabled TP/BE by default provides a clean baseline for evaluating the core logic.
Author: Awab_Hassan
Strategy

Indicator

Indicator

Indicator

Indicator

Gravity Well Trend | Lyro RSOverview:
Gravity Well Trend is a volume-weighted mean-reversion and trend tool built around a simple idea: the volume-weighted price center is where the market's "mass" sits, and price orbiting near it is effectively captured. A real trend only exists when price achieves sufficient distance from that center in ATR terms while the center itself is accelerating the same direction — an escape from the well, not just a temporary orbit. Three selectable signal modes let it run as a strict trend filter, a simple midline flip, or a band-reclaim system.
Key Features
Volume-Weighted Gravity Center: Calculates a volume-weighted moving average as the "center of mass" for price, forming the core reference line the rest of the indicator is built around.
Escape-Distance Trend Logic: In Trend mode, a bullish or bearish trend only confirms when price is far enough from the center (in ATR units) AND the center itself is moving the same direction — distance alone with a flat center doesn't count.
Three Signal Modes: Trend — flips only on a confirmed escape from the gravity well. Midline — simple long/short based on whether price is above or below the center. Bands — flips long on a cross above the lowest band and stays long until a cross below the highest band flips it short.
Layered Band Envelope: Plots an outer and inner band pair around the center (inner bands at half the outer width), with graded zone fills between center and bands for a clear visual sense of price's position within the well.
Gradient Strength Visualization: The gravity center line and candle coloring use a gradient blend based on how far price has traveled from center relative to the band width, giving an at-a-glance read on trend conviction.
Candle Coloring: Optionally recolors chart candles using the same gradient logic as the center line.
Customizable Visuals: Choose from 4 preset palettes — Classic, Mystic, Accented, Royal — or define your own custom bullish/bearish colors.
Built-In Signals: Automatically plots long/short labels on confirmed trend flips.
How It Works
Center Calculation – Computes a volume-weighted moving average of the source over the chosen length to establish the gravity center.
Distance Measurement – Measures the distance between price and the center in ATR units to gauge how far price has strayed from its center of mass.
Band Construction – Builds an outer band pair at the full Band Width setting and an inner pair at half that width, forming a layered envelope around the center.
Mode-Dependent Trend Logic – Trend mode requires both sufficient escape distance and a rising/falling center; Midline mode simply follows price relative to center; Bands mode uses crosses of the outer bands to flip and hold direction.
Visualization – Plots the gravity center with layered glow, the band envelope with graded fills, flip signal labels, and gradient-based candle coloring.
Practical Use
Trend Confirmation – Use Trend mode when you want to avoid acting on price simply drifting away from center without real directional follow-through in the center itself.
Simple Directional Bias – Use Midline mode for a straightforward above/below-center read when you want more frequent signals.
Range/Reclaim Trading – Use Bands mode to trade reclaims of extreme levels, holding a position until the opposite extreme is reclaimed.
Zone Awareness – Watch the graded band zones to see how extended price is relative to its recent volume-weighted center before committing to a trade.
Customization
Switch between Trend, Midline, and Bands signal modes to match your trading style.
Adjust Length to tune how responsive the gravity center is to recent price/volume.
Adjust Escape Distance to control how far price must travel (with a moving center) to confirm a trend in Trend mode.
Adjust Band Width and ATR Length to reshape the band envelope and its sensitivity.
Toggle bands, signal labels, and candle coloring independently.
Pick a preset palette or define fully custom bullish/bearish colors.
⚠️Disclaimer
This indicator is a tool for technical analysis and does not provide guaranteed results. It should be used in conjunction with other analysis methods and proper risk management practices. The creators of this indicator are not responsible for any financial decisions made based on its signals. Indicator

Advanced Market StructureAdvanced Market Structure
The Advanced Market Structure indicator is a comprehensive technical analysis script built for price action traders, Smart Money Concepts (SMC) practitioners, and market structure analysts. It helps traders map market context, spot key liquidity sweeps, and trade along institutional flow without cluttering the chart.
Key Features Overview
1. Smart Money Market Structure Engine
Automatically detects Break of Structure (BOS) for trend continuation and Change of Character (CHoCH) for potential trend reversals on valid swing points.
2. Intermediate Term Structure (ITH and ITL)
Replaces generic entry labels with institutional Intermediate Term Highs (ITH) and Intermediate Term Lows (ITL). These point out major liquidity pools where smart money often seeks liquidity.
3. Dynamic Candle Glow and Phase Detection
Calculates ATR and price expansion/contraction in real time to visually separate Consolidation phases from Expansion phases directly through candle coloring.
4. Auto Disappearing PDH and PDL
Plots Active Previous Day High (PDH) and Previous Day Low (PDL). As soon as price breaks through these liquidity levels, they automatically disappear to keep your workspace clean.
5. Dynamic 0.5 Equilibrium Range
Calculates the 50 percent Fibonacci Equilibrium line across recent swings, making it easy to identify Premium and Discount pricing zones.
6. Glowing Wave Line and Dashboard
Combines a dynamic Hull Moving Average trend line with a clean on screen dashboard displaying active structure context, market phase, and key level statuses.
Detailed How to Use Guide
Step 1: Determine the Macro Bias
Check the Glowing Wave Line color and recent market structure labels. A sequence of bullish BOS signals along with price staying above the Wave Line indicates a strong bullish bias.
Step 2: Identify Premium vs Discount Zones
Use the 0.5 Equilibrium Line to contextualize price position:
- Premium Zone (Above 0.5 EQ): Ideal area to search for short setups near Intermediate Term Highs (ITH) or Bearish CHoCH signals.
- Discount Zone (Below 0.5 EQ): Ideal area to search for long setups near Intermediate Term Lows (ITL) or Bullish CHoCH signals.
Step 3: Wait for Phase Transition
Observe the Candle Glow Engine. When candles transition from neutral or consolidation colors to strong trend expansion colors near an ITL or ITH level, it signals institutional participation.
Step 4: Liquidity Sweeps (PDH and PDL)
Watch how price interacts with Previous Day High and Low. A sweep followed by an immediate CHoCH back inside the daily range often offers high probability reversal scenarios.
Settings Overview and Customization
Candle Glow and Consolidation Settings
- Trend Momentum Lookback: Adjusts the sensitivity of the volatility calculation.
- Consolidation Range ATR Multiplier: Sets the sensitivity threshold for detecting squeeze or ranging market conditions.
Market Structure (BOS and CHoCH) Settings
- Structure Sensitivity (Pivot Length): Controls how sensitive the script is to swing points. Lower values (3 to 7) show lower timeframe structure, while higher values (10 to 20) show major structural points.
- Structure Colors: Full color customization for bullish and bearish structure lines and text labels.
Major Structure Labels (ITH and ITL) Settings
- Major Pivot Lookback: Defines the bar count required to mark Intermediate Term Highs and Lows.
- Label Customization: Customize colors and visibilities for ITH and ITL tags.
Previous Day High / Low and Equilibrium Settings
- Toggle Show Active PDH / PDL: Turn daily high/low tracking on or off.
- Equilibrium Lookback: Adjusts the swing period used to generate the 50 percent Fibonacci level.
Pro Tips for Effective Usage
Tip 1: Trade in the Direction of Macro Wave
For higher probability trades, take long positions when price is in a Discount Zone and the Wave Line is green. Take short positions when price is in a Premium Zone and the Wave Line is red.
Tip 2: Focus on Multi-Timeframe Confluence
Identify ITH/ITL levels on higher timeframes (such as 1-Hour or 4-Hour) and drop down to lower timeframes (5-Min or 15-Min) to spot CHoCH signals for refined entries.
Tip 3: Look for Liquidity Grab Reactions
Pay close attention when an active PDH or PDL line disappears. If price breaks the level and quickly creates a CHoCH in the opposite direction, it indicates a false breakout / liquidity sweep.
Things to Avoid
1. Avoid Trading During Consolidation
Do not take aggressive breakout entries when the Candle Glow engine highlights market consolidation. Wait for an explicit expansion candle close outside the range box.
2. Avoid Trading Counter Trend at Equilibrium
Do not short right at the 0.5 Equilibrium line if the overall structural trend is strongly bullish with consecutive bullish BOS signals.
3. Avoid Over Sensitivity on Scalping Timeframes
Do not set the Structure Sensitivity too low (below 3) on sub-minute charts, as minor price noise may generate excess structural markings.
Disclaimer
This tool is built strictly for educational and analytical purposes. It does not provide financial advice or direct trading signals. Always practice proper risk management and position sizing. Indicator

Indicator

Indicator

Moving Average Ribbon - MTFMOVING AVERAGE RIBBON (MTF)
A clean, lightweight ribbon of four independent moving averages — everything you normally need from several separate MA scripts, combined into a single indicator slot.
Instead of loading four copies of a basic MA indicator, this script lets you configure each line completely on its own, including the timeframe it is calculated on.
FEATURES
• 4 independent moving averages. Each one can be enabled or disabled individually, and a disabled MA is fully removed from the chart and the status line.
• 5 MA types per line: SMA, EMA, SMMA (RMA), WMA, and VWMA. Every MA can use a different type — for example an EMA for the fast line and an SMA for the slow line.
• Custom source per line. Choose close, open, hl2, hlc3, or any other series available in the source dropdown, separately for each MA.
• Custom length and color per line.
• Per-MA multi-timeframe (MTF). Each moving average has its own MTF toggle and timeframe field. Enable MTF on a single line to overlay, for example, the daily 200 MA on a 15-minute chart, while the other three lines stay on the chart timeframe.
• Compact settings layout. All parameters for one MA sit on a single inline row, so the settings panel stays readable, and the inputs for a disabled MA are greyed out.
DEFAULT CONFIGURATION
MA #1 — SMA, length 5, source close
MA #2 — SMA, length 20, source close
MA #3 — SMA, length 50, source close
MA #4 — SMA, length 200, source close
All four are enabled by default with MTF turned off, so out of the box the indicator behaves as a standard 5 / 20 / 50 / 200 ribbon on the chart timeframe. Every value can be changed in the settings.
ABOUT THE MTF CALCULATION
Higher-timeframe values are requested with lookahead disabled, so no future data is used and the plotted history matches what would have been visible in real time. Higher-timeframe lines update as the higher-timeframe bar develops, and become final when that bar closes. The indicator also supports the built-in timeframe selector in the settings, with gaps enabled, if you prefer to shift the whole indicator to another resolution at once.
HOW TO USE IT
• Use the fast and slow lines together to read trend direction and momentum: price above the ribbon with the lines stacked in order suggests an uptrend, the reverse suggests a downtrend.
• Watch crossovers between two lines as a classic trend-change reference (for example 20 over 50).
• Use the MTF option to keep a higher-timeframe level of reference — such as the daily 200 MA — visible while you work on a lower timeframe.
This indicator is a visualization tool only. It does not generate buy or sell signals and should be combined with your own analysis and risk management.
Indicator

Indicator

Trend-Aligned Oscillator Reversal Engine Comprehensive Guide: Trend-Aligned Oscillator Reversal Engine
Introduction: What is this script and its primary purpose?
The "Trend-Aligned Oscillator Reversal Engine" is a highly sophisticated, multi-layered custom indicator written in Pine Script for the PulseWire platform. Unlike traditional single-metric indicators that often produce false signals in choppy markets, this script functions as a complete, self-contained trading system.
Its primary purpose is to identify high-probability market reversal points by combining momentum exhaustion with strict trend-following filters. The script aims to solve a common dilemma for traders: getting into a reversal early enough to maximize profit, while ensuring the broader market structure supports the trade. By demanding a "confluence of evidence" from multiple technical sources before issuing a buy or sell signal, it minimizes the risk of catching falling knives or shorting into parabolic uptrends. Furthermore, it includes automated alert conditions, making it seamlessly compatible with external platforms via webhooks, Telegram, or API integrations for automated trading.
Working Mechanism: How does it detect trading signals?
The script generates Buy and Sell signals through a complex, dual-engine architecture combined with a dynamic entry delay system. It operates using three distinct technical phases:
1. The Oscillator Reversal Engine (The Trigger)
This engine acts as the primary signal detector, scanning for moments when the market is overextended and ready to snap back. It aggregates data from four classic momentum oscillators:
RSI (Relative Strength Index): Set to a standard 14-period lookback, it detects extreme price levels. A long signal requires the RSI to cross back above the 30 (oversold) threshold, while a short signal triggers when crossing below 70 (overbought).
Stochastic Oscillator (14, 3, 3):This measures closing prices relative to the high-low range. It looks for bullish %K and %D crossovers below the 20 level and bearish crossunders above the 80 level.
Oscillator MACD (12, 26, 9): Identifies shifts in short-term momentum via the crossover or crossunder of the fast MACD line and the signal smoothing line.
CCI (Commodity Channel Index - 20): Detects when cyclical boundaries are breached, triggering upon crossing the -100 or +100 levels.
Confluence Scoring: Rather than relying on just one metric, the script assigns a score of 1 to 4 based on how many oscillators trigger simultaneously. The user can define the `osci_min_score` (default is 1) required to generate a baseline reversal signal.
2. The Trend Confirmation Engine (The Filter)
If the `use_trend_filter` setting is enabled, a reversal signal is completely blocked unless the broader market trend aligns with the trade direction. This engine evaluates five distinct trend indicators:
EMA (50-period): Assesses if the current price is above or below the baseline moving average.
ADX & DMI (14-period): Ensures there is actual trend strength (ADX > 20) and identifies whether buyers (+DI) or sellers (-DI) are in control.
Trend MACD: Validates medium-term momentum direction relative to the zero line.
Supertrend : Evaluates volatility-based trailing support and resistance bands.
Ichimoku Cloud: Checks if the price is trading above the Kumo Cloud (bullish) or below it (bearish).
Trend Scoring:Similar to the oscillators, it calculates a trend score out of 5. By default, at least 3 out of 5 indicators (`trend_min_score`) must agree to confirm the trend's legitimacy.
3. The Retest State Machine (Entry Optimization)
When a trend shift occurs, the script features an optional "Retest Mode". Instead of entering immediately on a breakout—which often leads to fake-outs—the system waits for the price to retest a specific support/resistance level. This level is calculated dynamically using a 14-period Average True Range (ATR) multiplier. The script will wait for a maximum number of candles (default is 3) for this retest to happen before validating or discarding the setup.
How to Use: Recommended Settings and Suitable Markets
Recommended Configurations:
For Conservative Traders: Increase the `osci_min_score` to 2 or 3. This means at least two or three oscillators (e.g., RSI and MACD) must agree simultaneously, drastically reducing false signals. Always keep `use_trend_filter` set to `true`.
Trade Direction Filter: If you are trading in a confirmed macro bull market (like Bitcoin leading up to a halving), set the `trade_direction` to "Buy Only". This ensures you only catch the dips in a larger uptrend and prevents you from fighting the primary market direction.
Retest Mode Adjustments: In highly volatile conditions, leave "Enable Retest Mode" checked with an ATR multiplier of 1.0 to secure better entry prices. In aggressive breakout markets where pullbacks are rare, you may want to disable this feature so you do not miss fast-moving trades.
Suitable Markets and Timeframes:
Because of its reliance on confluence, trend strength, and ATR volatility, this indicator is highly versatile.
Markets: It performs exceptionally well in the Forex market (e.g., EUR/USD, GBP/JPY) where trends and mean-reversions are clearly defined. It is equally effective in Crypto (BTC, ETH) and Indices (S&P 500, NASDAQ) because the rigorous trend-filtering engine automatically strips out the "noise" and fake-outs typical in high-volatility assets.
Timeframes:The script is optimized for medium to higher timeframes. The 15-minute (15m), 1-hour (1H), and 4-hour (4H) charts are ideal. Using it on lower timeframes (like the 1-minute chart) is not recommended, as micro-market noise can prematurely trigger the oscillators before the macro-trend indicators have time to align. Indicator

Confluence Trend and Fibo Reversal SystemAn In-Depth Overview of the "Confluence Trend and Fibo Reversal System"
Introduction: The Purpose and Core Architecture
The "Confluence Trend and Fibo Reversal System" is a sophisticated, highly adaptable Pine Script trading indicator designed to dynamically navigate fluctuating market conditions. The primary objective of this script is to solve a fundamental problem in technical analysis: the tendency of trend-following indicators to produce false signals during sideways markets, and the failure of mean-reversion oscillators during strong trends. To achieve this, the indicator operates as a dual-regime trading algorithm. It constantly analyzes price action to determine whether the current market environment is trending or ranging (sideways). Based on this real-time assessment, the script autonomously switches its internal logic, deploying either a momentum-based confluence engine for trends or a reversal-based engine strictly filtered by Fibonacci retracement levels for sideways markets.
Operating Mechanisms: How the Indicator Generates Signals
The technical architecture of this indicator is divided into four distinct analytical engines that work together to validate trading signals.
1. The Market Regime Filter (Range Detection)
Before any signal is generated, the system calculates a "Range Score" to determine the market state. It evaluates six specific technical conditions:
ADX (Average Directional Index): Checks if the ADX value is below 25, indicating weak trend strength.
Bollinger Bands Position: Verifies if the closing price is contained securely within the upper and lower bands.
Bollinger Bandwidth (BBW): Measures volatility by checking if the current bandwidth is narrower than its 20-period moving average.
RSI (Relative Strength Index): Checks if the RSI is hovering in a neutral zone between 40 and 60.
Stochastic Oscillator: Confirms that the Stochastic K-line is resting in a non-extreme zone between 20 and 80.
EMA Convergence:Measures the gap between the 20-period and 50-period Exponential Moving Averages, checking if they are tightly converged within half of the Average True Range (ATR).
If the total score meets a user-defined threshold (defaulting to 4 out of 6), the system classifies the market as "Ranging" and activates the Reversal engine; otherwise, it defaults to the Trend engine.
2. The Trend Engine (Confluence Scoring)
When the market is clearly trending, the script relies on a strict multi-indicator confluence system to prevent premature entries. It generates a bullish or bearish score out of five possible points:
Price positioning relative to the 50-period EMA.
Directional dominance using the ADX (+DI vs -DI).
Momentum confirmation via MACD baseline crossovers.
Trend alignment with the Supertrend indicator.
Price placement above or below the Ichimoku Kumo Cloud.
A final buy or sell signal in trend mode is only triggered if the accumulated score meets the "Minimum Confluence Score" threshold (defaulting to 4 out of 5).
3. The Reversal & Fibonacci Engine
If the market is ranging, the script hunts for mean-reversion opportunities by scanning for specific price action anomalies and oscillator extremes. It looks for Bullish/Bearish Engulfing candles, Pinbars (Hammers and Shooting Stars), RSI overbought/oversold crossovers, Stochastic extreme crossovers, and Bollinger Band boundary breakouts.
Crucially, these reversal patterns are deemed invalid unless they occur in close proximity to an automatically generated Fibonacci level. The script identifies the highest high and lowest low over a 100-bar lookback period to draw dynamic Fibonacci retracement lines (0.000 to 1.000). A reversal signal is only approved if the price action happens within a tight percentage tolerance zone around these key Fibonacci levels.
4. The Retest Engine
To drastically reduce false breakouts, the script features a built-in "Retest Mode". Instead of firing a buy or sell signal immediately when conditions are met, the script calculates a target "retest price" offset by an ATR multiplier. It will then hold the pending signal in memory for a maximum number of candles (defaulting to 4). The final execution signal is only printed on the chart if the price pulls back to successfully retest this calculated ATR level, proving the validity of the breakout.
Implementation and Usage Guidelines
Recommended Settings
Trade Direction: It is highly recommended to leave the trade direction set to "Both" to allow the dynamic regime filter to operate at its full potential. However, if trading against a higher timeframe macroeconomic trend, users can restrict the system to "Buy Only" or "Sell Only".
Retest Mode: Keep "Enable Retest Mode" activated. While it may cause you to miss trades that instantly aggressively rally, it will save you from substantial losses caused by "fake-out" signals.
Confluence Threshold: For aggressive traders, lowering the Trend Minimum Confluence Score to 3 will yield more signals. For conservative traders, leaving it at 4 or 5 ensures that only the highest probability momentum shifts are traded.
Visual Enhancements: Keep the "Highlight Range Market Background" enabled. This feature turns the chart background orange during sideways markets, providing excellent visual context as to why the indicator is currently ignoring standard trend breakouts.
Suitable Markets and Timeframes**
Because the "Confluence Trend and Fibo Reversal System" actively adapts to volatility and structural shifts rather than relying on static logic, it is exceptionally versatile. It is well-suited for high-liquidity markets such as major Forex pairs (EUR/USD, GBP/USD), large-cap Cryptocurrencies (Bitcoin, Ethereum), and major Equity indices. Due to its reliance on 100-period lookbacks for Fibonacci mapping and 50-period EMAs for trend detection, the indicator performs optimally on medium to higher timeframes—specifically the 1-Hour (H1), 4-Hour (H4), and Daily (D1) charts—where market noise is minimal, and true institutional support and resistance zones are respected. Indicator

5 Trend Indicators Combo IndicatorThe 5 Trend Indicators Combo with Retest Logic: A Comprehensive Guide
The "5 Trend Indicators Combo Indicator" is an advanced, multi-faceted technical analysis tool built using Pine Script for PulseWire. Its primary purpose is to identify high-probability trend reversals and continuations by aggressively filtering out market noise and minimizing false breakout signals. Instead of relying on a single, isolated metric—which can often be misleading—this script utilizes a robust "confluence" methodology. It systematically evaluates five distinct, highly respected trend-following indicators, aggregating their individual statuses into a unified scoring system. Furthermore, it elevates standard signal generation by incorporating an intelligent pullback (retest) mechanism, explicitly designed to optimize entry prices so that traders do not buy at the absolute top or sell at the bottom of a sudden, volatile price spike. Additionally, it features a built-in graphical dashboard that allows traders to instantly monitor the bullish or bearish status of all five indicators in real-time.
Working Mechanism: How does it detect trading signals?
The core engine of this script evaluates five technical pillars, each contributing a maximum of one point to a total "Bull Score" or "Bear Score":
1. Exponential Moving Average (EMA): Defaulted to a 50-period length, the EMA establishes the chart's baseline directional bias. A bullish point is awarded if the current closing price is strictly above the EMA, and a bearish point is given if it is below.
2. Average Directional Index (ADX) & DMI: This component measures the absolute strength and direction of a trend. To score a point, the ADX value must exceed a specific threshold (defaulted to 20), acting as a strict filter to ensure the market is actually trending rather than chopping in a sideways range. Once this threshold is met, the Directional Indicators dictate the bias: +DI must be greater than -DI for a bullish point, and vice versa for a bearish point.
3. Moving Average Convergence Divergence (MACD): Operating with standard 12, 26, and 9 periods, the MACD assesses momentum shifts. The script requires strict criteria here: for a bullish score, the MACD line must be above the Signal line *and* above the zero baseline. Bearish points require the MACD line to be completely below both.
4. Supertrend:Utilizing a multiplier of 3.0 and an ATR period of 10, the Supertrend acts as a volatility-adjusted trailing stop. It awards a point depending on whether the current trend is mathematically calculated as bullish (direction < 0) or bearish (direction > 0).
5. Ichimoku Cloud (Kumo): The script analyzes the relationship between the closing price and the Kumo (Cloud), which is defined by Senkou Span A and Span B projected 26 periods into the future. A bullish point is granted only if the price has successfully broken out above the top boundary of the cloud, signifying dominant long-term momentum. A bearish point requires a breakdown below the bottom boundary.
Once the overall score is tallied (ranging from 0 to 5), the script compares it against a user-defined "Minimum Confluence Score". When the score crosses this threshold, an initial trend signal is generated. However, the script's standout technical feature is its "Retest / Pullback" logic. Instead of firing the final execution alert immediately upon the breakout, the script enters a "pending" state. It calculates a dynamic retracement target using an Average True Range (ATR) multiplier. For a buy signal, the price must briefly retrace down to `Close - (ATR * Multiplier)`. The script waits for a maximum number of candles (default is 3) for this pullback to occur. If the price successfully touches this retest level, a highly optimized, safe entry is signaled. If the time expires without a retest, the script automatically fires a delayed entry to ensure the trader does not miss a runaway trend.
How to Use: Optimal Settings and Suitable Markets
To deploy this indicator effectively, traders should focus on optimizing the 'Minimum Confluence Score'. A score of 3 is the recommended baseline, offering a healthy balance between trade frequency and signal accuracy. Increasing this to 4 or 5 will result in much stricter, albeit fewer, high-conviction signals. The Retest ATR Multiplier and Max Wait Bars must be adjusted according to the timeframe; faster timeframes might require smaller ATR multipliers to successfully catch brief micro-pullbacks before the timer expires.
Regarding suitable markets, this indicator is exclusively designed for trending environments. It performs exceptionally well in high-liquidity, directional markets such as major Forex pairs (e.g., EUR/USD, GBP/JPY), large-cap cryptocurrencies (Bitcoin, Ethereum), and major stock indices (S&P 500, NASDAQ). Because it relies heavily on trend-following logic and moving averages, it is most appropriate for medium to higher timeframes, particularly the 1-hour, 4-hour, and Daily charts. Using it on extremely low timeframes (like 1-minute or 3-minute charts) may expose it to excessive intraday noise and erratic wicks, though the ADX filter and Retest mechanism will actively attempt to mitigate those risks. Ultimately, this script transforms a standard chart into a highly systematic, rule-based trading system. Indicator
