Market Structure Trailing Stop MTF [Inspired by LuxAlgo]# Market Structure Trailing Stop MTF
**OPEN-SOURCE SCRIPT**
*208k+ views on original · Modified for MTF Support*
This indicator is a direct adaptation of the renowned **Market Structure Trailing Stop** by **LuxAlgo** (original script: [Market Structure Trailing Stop ]()). The core logic remains untouched, providing dynamic trailing stops based on market structure breaks (CHoCH/BOS). The **only modification** is the addition of **Multi-Timeframe (MTF) support**, allowing users to apply the trailing stops and structures from **higher timeframes (HTF)** directly on their current chart. This enhances usability for traders analyzing cross-timeframe confluence without switching charts.
**Special thanks to LuxAlgo** for releasing this powerful open-source tool under CC BY-NC-SA 4.0. Your contributions to the TradingView community have inspired countless traders—grateful for the solid foundation!
## 🔶 How the Script Works: A Deep Dive
At its heart, this indicator detects **market structure shifts** (bullish or bearish breaks of swing highs/lows) and uses them to generate **adaptive trailing stops**. These stops trail the price while protecting profits and acting as dynamic support/resistance levels. The MTF enhancement pulls this logic from user-specified higher timeframes, overlaying HTF structures and stops on the lower timeframe chart for seamless multi-timeframe analysis.
### Core Logic (Unchanged from LuxAlgo's Original)
1. **Pivot Detection**:
- Uses `ta.pivothigh()` and `ta.pivotlow()` with a user-defined lookback (`length`) to identify swing highs (PH) and lows (PL).
- Coordinates (price `y` and bar index/time `x`) are stored in persistent variables (`var`) for tracking recent pivots.
2. **Market Structure Detection**:
- **Bullish Structure (BOS/CHoCH)**: Triggers when `close > recent PH` (break above swing high).
- If `resetOn = 'CHoCH'`, resets only on major shifts (Change of Character); otherwise, on all breaks.
- Sets trend state `os = 1` (bullish) and highlights the break with a horizontal line (dashed for CHoCH, dotted for BOS).
- Initializes trailing stop at the local minimum (lowest low since the pivot) using a backward loop: `btm = math.min(low , btm)`.
- **Bearish Structure**: Triggers when `close < recent PL`, mirroring the bullish logic (`os = -1`, local maximum for stop).
- Structure state `ms` tracks the break type (1 for bull, -1 for bear, 0 neutral), resetting based on user settings.
3. **Trailing Stop Calculation**:
- Tracks **trailing max/min**:
- On new bull structure: Reset `max = close`.
- On new bear: Reset `min = close`.
- Otherwise: `max = math.max(close, max)` / `min = math.min(close, min)`.
- **Stop Adjustment** (the "trailing" magic):
- On fresh structure: `ts = btm` (bull) or `top` (bear).
- In ongoing trend: Increment/decrement by a percentage of the max/min change:
- Bull: `ts += (max - max ) * (incr / 100)`
- Bear: `ts += (min - min ) * (incr / 100)`
- This creates a **ratcheting effect**: Stops move favorably with the trend but never against it, converging toward price at a controlled rate.
- **Visuals**:
- Plots `ts` line colored by trend (teal for bull, red for bear).
- Fills area between `close` and `ts` (orange on retracements).
- Draws structure lines from pivot to break point.
4. **Edge Cases**:
- Variables like `ph_cross`/`pl_cross` prevent multiple triggers on the same pivot.
- Neutral state (`ms = 0`) preserves prior `max/min` until a new structure.
### MTF Enhancement (Our Addition)
- **request.security() Integration**:
- Wraps the entire core function `f()` in a security call for each timeframe (`tf1`, `tf2`).
- Returns HTF values (e.g., `ts1`, `os1`, structure times/prices) to the chart's context.
- Uses `lookahead=barmerge.lookahead_off` for accurate historical repainting-free data.
- Structures are drawn using `xloc.bar_time` to align HTF lines precisely on the LTF chart.
- **Multi-Output Handling**:
- Separate plots/fills/lines for each TF (e.g., `plot_ts1`, `plot_ts2`).
- Colors and toggles per TF to distinguish HTF1 (e.g., teal/red) from HTF2 (e.g., blue/maroon).
- **Benefits**: Spot HTF bias on LTF entries, e.g., enter longs only if both TF1 (1H) and TF2 (4H) show bullish `os=1`.
This keeps the script lightweight—**no repainting, max 500 lines**, and fully compatible with LuxAlgo's original behavior when TFs are set to the chart's timeframe.
## 🔶 SETTINGS
### Core Parameters
- **Pivot Lookback** (`length = 14`): Bars left/right for pivot detection. Higher = smoother structures, fewer signals; lower = more noise.
- **Increment Factor %** (`incr = 100`): Speed of stop convergence (0-∞). 100% = full ratchet (mirrors max/min exactly); <100% = slower trail, reduces whipsaws.
- **Reset Stop On** (`'CHoCH'`): `'CHoCH'` = Reset only on major reversals (dashed lines); `'All'` = Reset on every BOS/CHoCH (tighter stops).
### MTF Support
- **Timeframe 1** (`tf1 = ""`): HTF for first set (e.g., "1H"). Empty = current chart.
- **Timeframe 2** (`tf2 = ""`): Second HTF (e.g., "4H"). Enables dual confluence.
### Display Toggles
- **Show Structures** (`true`): Draws horizontal lines for breaks (per TF colors).
- **Show Trailing Stop TF1/TF2** (`true`): Plots the stop line.
- **Show Fill TF1/TF2** (`true`): Area fill between close and stop.
### Candle Coloring (Optional)
- **Color Candles** (`false`): Enables custom `plotcandle` for body/wick/border.
- **Candle Color Based On TF** (`"None"`): `"TF1"`, `"TF2"`, or none. Colors bull trend green, bear red.
- **Candle Colors**: Separate inputs for bull/bear body, wick, border (e.g., solid green body, transparent wick).
### Alerts
- **Enable MS Break Alerts** (`false`): Notifies on structure breaks (bull/bear per TF) **only on bar close** (`barstate.isconfirmed` + `alert.freq_once_per_bar_close`).
- **Enable Stop Hit Alerts** (`false`): Triggers on stop breaches (long/short per TF), using `ta.crossunder/crossover`.
### Colors
- **TF1 Colors**: Bullish (teal), Bearish (red), Retracement (orange).
- **TF2 Colors**: Bullish (blue), Bearish (maroon), Retracement (orange).
- **Area Transparency** (`80`): Fill opacity (0-100).
## 🔶 USAGE
Trailing stops shine in **trend-following strategies**:
- **Entries**: Use structure breaks as signals (e.g., long on bullish BOS from HTF1).
- **Exits**: Trail stops for profit-locking; alert on hits for automation.
- **Confluence**: Overlay HTF1 (e.g., 1H) for bias, HTF2 (e.g., Daily) for major levels—enter LTF only on alignment.
- **Risk Management**: Lower `incr` avoids early stops in chop; reset on `'All'` for aggressive trailing.
! (i.imgur.com)
*HTF1 shows bullish structure (teal line), trailing stop ratchets up—long entry confirmed on LTF pullback.*
! (i.imgur.com)
*TF1 (blue) bearish, TF2 (red) neutral—avoid shorts until alignment.*
! (i.imgur.com)
*Colored based on TF1 trend: Green bodies on bull `os=1`.*
Pro Tip: Test on demo—pair with LuxAlgo's other tools like Smart Money Concepts for full structure ecosystem.
## 🔶 DETAILS: Mathematical Breakdown
On bullish break:
- Local min: `btm = ta.lowest(n - ph_x)` (optimized loop equivalent).
- Stop init: `ts = btm`.
- Update: `Δmax = max - max `, `ts_new = ts + Δmax * (incr/100)`.
Bearish mirrors with `Δmin` (negative, so decrements `ts`).
In MTF: HTF `time` aligns lines via `line.new(htf_time, level, current_time, level, xloc.bar_time)`.
No logs/math libs needed—pure Pine v5 efficiency.
## Disclaimer
This is for educational purposes. Not financial advice. Backtest thoroughly. Original by LuxAlgo—modify at your risk. See TradingView's (www.tradingview.com). Licensed under CC BY-NC-SA 4.0 (attribution to LuxAlgo required).
