OPEN-SOURCE SCRIPT

Trend-cycle reversion (multi-timeframe)

33
Trend-cycle reversion (multi-timeframe) is a mean-reversion “stretch” gauge built around a simple idea: price often deviates from its recent path (trend + dominant swing rhythm), and those deviations become more actionable when you scale them by volatility and express them as a standardized score.

This script models the last N bars as:
1) a linear trend (to capture drift), plus
2) a single dominant cycle (to capture the most prominent oscillation inside the same window).

It then measures how far current price is from the model’s next-bar projection, normalizes that distance by ATR (volatility), and finally converts the result into a rolling Z-score. The output is displayed as a multi-timeframe dashboard so you can see “stretch vs. fit” across several time compressions at once.

------------------------------------------------------------
What you see on the chart
------------------------------------------------------------
The indicator draws a table (overlay) with up to 12 rows (configurable), one per timeframe from your CSV list.

Each row shows:
• TF: The timeframe being evaluated (e.g., 1, 5, 15, 60, 240, D).
• Z: The current Z-score of the volatility-scaled model gap on that timeframe.
• State: A simple interpretation using your Z threshold:
- “Short ▼” when Z > +threshold (price is extended above the model path)
- “Long ▲” when Z < −threshold (price is extended below the model path)
- “Hold •” when inside the band (not unusually stretched)

Colors follow the same logic: red for high positive Z, green for high negative Z, gray when neutral or unavailable.

Important: “Long/Short” here describes the direction of mean-reversion pressure (over/under the fitted path), not a complete trading system by itself.

------------------------------------------------------------
How it works (plain-English math)
------------------------------------------------------------
1) Optional log transform
If “Fit on log(price)” is enabled, the model runs on log(price) instead of raw price. This is often useful for markets that behave multiplicatively (large percentage moves, long-term exponential growth), because distances become closer to “percent-like” rather than absolute dollars.

2) Trend fit (linear regression in the window)
Over the last Window Length bars, the script estimates a straight-line trend. Think of this as the baseline path that best explains the window if you ignore swings.

3) Cycle search (best period by least-squares error)
After removing the linear trend, the script searches for a single sinusoidal cycle period between:
• Min Period and Max Period (in bars), stepping by Period Step.
For each candidate period, it computes the best-fitting sine+cosine components and measures the remaining error (SSE). The period with the smallest SSE is selected as the “best” cycle for that window.

To reduce recalculation cost and to keep the chosen cycle from flapping every bar, the script re-runs this period search only every “Re-search best period every N bars”. Between searches, it keeps using the last best period.

4) Next-bar projection and “gap”
Using the fitted trend + fitted cycle, the script projects the model value one bar ahead (relative to the window indexing). It then computes:

gap = (current value) − (projected value)

If “Invert sign” is enabled, the gap is multiplied by −1. This doesn’t change magnitude, it only flips interpretation (useful if you prefer the opposite sign convention).

5) Volatility scaling via ATR
The raw gap is divided by ATR to make it comparable across symbols and regimes. If you are fitting on log(price), ATR is also computed in log space using a log-based true range, then smoothed similarly (so the scale is consistent).

This produces a “gap in ATR units”.

6) Z-score standardization
Finally, the script computes a rolling Z-score of the ATR-scaled gap over “Z-score length”:

Z = (gapATR − mean(gapATR)) / stdev(gapATR)

This is what appears in the table. The Z-score answers: “How unusual is today’s model deviation compared to the last Z-score length observations?”

------------------------------------------------------------
How to interpret the Z-score
------------------------------------------------------------
Z near 0:
Price is close to the model path relative to recent volatility (nothing unusual).

Z above +threshold:
Price is meaningfully ABOVE the fitted path (stretched up). This can be read as elevated downside mean-reversion pressure — but it can also persist during strong trends.

Z below −threshold:
Price is meaningfully BELOW the fitted path (stretched down). This can be read as elevated upside mean-reversion pressure — but it can also persist during fast selloffs.

A practical way to use this indicator is to treat it as a “context filter” or “risk tool”:
• Fading extremes: look for mean-reversion setups when Z is beyond the threshold and price action confirms (e.g., momentum stalls, structure breaks, volatility contraction/expansion cues).
• Trend-aware reversion: only take “reversion” signals in the direction permitted by your separate trend filter (higher-timeframe trend, moving average regime, market structure, etc.).
• Take-profit / risk management: in a trend-following strategy, extremes can be used as partial profit zones or as “don’t chase here” warnings.

------------------------------------------------------------
Multi-timeframe (MTF) notes
------------------------------------------------------------
Each table row is computed with request.security() on that timeframe with no lookahead, so it is not using future bars to form the value.

However, like any live indicator, the value for an actively forming bar can change until that bar closes (especially on the lower timeframes). Also, higher-timeframe rows update when that higher-timeframe bar updates/closes.

------------------------------------------------------------
Inputs (what to change first)
------------------------------------------------------------
If you only change a few settings, start here:

• Window Length:
Controls how much history the model uses. Larger = smoother/stabler, but slower to adapt.

• Min/Max Period + Step:
Controls the cycle search range and granularity.
- Wider ranges can capture more possibilities but cost more computation.
- Smaller steps can find a closer match but also cost more.

• Re-search every N bars:
Higher = faster performance and more stability; lower = more adaptive but can be noisier.

• ATR length (scale gap):
Controls the volatility scale. Shorter reacts faster to volatility changes; longer is steadier.

• Z-score length:
Controls how “rare” extremes are. Longer lengths make Z more stable, but require more history and adapt slower to regime shifts.

• Z threshold:
Defines when the table labels “Long/Short”. Common choices are 1.5–2.5 depending on how selective you want extremes to be.

• Timeframes (CSV) + Max table rows:
Controls what you see in the dashboard.

------------------------------------------------------------
Limitations and expectations
------------------------------------------------------------
This is a single-cycle, windowed model. Markets can be multi-cycle, non-sinusoidal, or structurally shifting; in those cases the “best period” is simply the best approximation inside the window, not a guarantee of a true underlying rhythm.

Z-score extremes are not automatic reversal calls. In strong trends or during volatility shocks, Z can stay extreme longer than expected. Use this as a measurement tool, then combine it with your own confirmation and risk management.

This indicator is for analysis/education and does not provide financial advice.

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน