Indicator · Pine Script v5 · On the chart

Market Structure Trailing Stop [LuxAlgo]

by theonetrade· code credited to LuxAlgo

Market Structure Trailing Stop [LuxAlgo] identifies pivot highs and lows to track market structure breaks and Change of Character (CHoCH) events.

View on GitHub

GitHub stars34on the repository
Pine versionv5runs as is
Lines of code133
Settings8inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

133 lines of Pine Script v5 from assets/indicator/bit-exact/market_structure_trailing_stop_luxalgo_c4Z9xThG.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

market_structure_trailing_stop_luxalgo_c4Z9xThG.pine
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator("Market Structure Trailing Stop [LuxAlgo]", overlay = true, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length  = input(14, 'Pivot Lookback')
incr    = input.float(100, 'Increment Factor %', minval = 0)
resetOn = input.string('CHoCH', 'Reset Stop On', options = ['CHoCH', 'All'])
showMS  = input(true, "Show Structures")

//Style
bullCss    = input(color.teal, 'Bullish MS'                           , group = 'Colors')
bearCss    = input(color.red, 'Bearish MS'                            , group = 'Colors')
retCss     = input(#ff5d00, 'Retracement'                             , group = 'Colors')
areaTransp = input.int(80, 'Area Transparency', minval = 0, maxval = 100, group = 'Colors')

//------------------------------------------------------------------------------
//Global variables
//-----------------------------------------------------------------------------{
var float ph_y = na , var int ph_x = na
var float pl_y = na , var int pl_x = na
var float top = na  , var float btm = na
var ph_cross = false, var pl_cross = false

var float max = na
var float min = na
var float ts = na

var os = 0
ms = 0

//------------------------------------------------------------------------------
//Detect pivots and get coordinates
//-----------------------------------------------------------------------------{
n = bar_index
ph = ta.pivothigh(length, length)
pl = ta.pivotlow(length, length)

if ph 
    ph_y := ph
    ph_x := n - length
    ph_cross := false

if pl 
    pl_y := pl
    pl_x := n - length
    pl_cross := false

//-----------------------------------------------------------------------------}
//Bullish structures
//-----------------------------------------------------------------------------{
if close > ph_y and not ph_cross
    if resetOn == 'CHoCH'
        ms := os == -1 ? 1 : 0
    else
        ms := 1

    ph_cross := true

    //Highilight bullish MS
    if showMS
        line.new(ph_x, ph_y, n, ph_y
          , color = bullCss
          , style = os == -1 ? line.style_dashed : line.style_dotted)

    os := 1

    //Search for local minima
    btm := low
    for i = 0 to (n - ph_x)-1
        btm := math.min(low[i], btm)

//-----------------------------------------------------------------------------}
//Bearish structures
//-----------------------------------------------------------------------------{
if close < pl_y and not pl_cross
    if resetOn == 'CHoCH'
        ms := os == 1 ? -1 : 0
    else
        ms := -1

    pl_cross := true

    //Highilight bearish MS
    if showMS
        line.new(pl_x, pl_y, n, pl_y
          , color = bearCss
          , style = os == 1 ? line.style_dashed : line.style_dotted)

    os := -1

    //Search for local maxima
    top := high
    for i = 0 to (n - pl_x)-1
        top := math.max(high[i], top)

//-----------------------------------------------------------------------------}
//Trailing stop
//-----------------------------------------------------------------------------{
//Trailing max/min
if ms == 1
    max := close
else if ms == -1
    min := close
else
    max := math.max(close, max)
    min := math.min(close, min)

//Trailing stop
ts := ms == 1 ? btm
  : ms == -1 ? top
  : os == 1 ? ts + (max - max[1]) * incr / 100
  : ts + (min - min[1]) * incr / 100

//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
css = ms ? na 
  : os == 1 ? bullCss
  : bearCss

plot_price = plot(close, editable = false, display = display.none)
plot_ts    = plot(ts, 'Trailing Stop', color = css)

css_area = (close - ts) * os < 0 ? retCss
  : css

fill(plot_price, plot_ts, color.new(css_area, areaTransp))

//-----------------------------------------------------------------------------}

Overview

Market Structure Trailing Stop [LuxAlgo] calculates a dynamic trailing stop line based on historical local extrema relative to structural levels and plots structural break lines directly on the price chart. Users can adjust the pivot lookback period, toggle market structure visualization, select whether to reset the trailing stop on CHoCH or all breaks, and customize transparency and color settings. Pivot confirmation requires a lookback delay equal to the pivot length.

Details

Published by

theonetrade on GitHub

Code credit

LuxAlgo, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Pivot Lookbackint14length
Increment Factor %float100incr
Reset Stop OnstringCHoCHresetOn
Show StructuresbooltrueshowMS
Bullish MScolorcolor.tealbullCss
Bearish MScolorcolor.redbearCss
Retracementcolor#ff5d00retCss
Area Transparencyint80areaTransp
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

This Pine Script indicator plots a ZigZag on the price chart. It identifies reversal points when price moves more than a set percentage from the last pivot. The script calculates forecasts using zigzag data and labels detected geometric patterns including harm

Indicator v4 TrendSupport & resistance
228 stars

This indicator plots market structure on the price chart by identifying swing highs and lows. It connects these points with lines to visualize trend direction and detect Break of Structure (BOS) when price breaks a prior swing in the current trend. Change of C

Indicator v6 TrendSupport & resistance
Updated 4 months ago · None stated GitHub repository of Market Structure - BOS & CHoCH

Open Source Fractal

by cantolab
183 stars

This indicator implements the Fractal Model concept to plot market structure shifts, liquidity sweeps, and Change in State of Delivery (CISD) levels. It overlays custom higher-timeframe candle previews, open prices, and time markers directly on the price chart

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 3 months ago · MIT GitHub repository of Open Source Fractal
56 stars

BigBeluga Smart Money Concepts identifies and overlays market structure and volumetric order blocks directly on the price chart. It analyzes market swings, trend sweeps, and mapping structure using customizable pivot lengths and calculation modes. The indicato

Indicator v5 SMC / ICT / price actionSupport & resistance
Updated 3 months ago · None stated GitHub repository of BigBeluga - Smart Money Concepts
53 stars

Apex Trend & Liquidity Master calculates a trend cloud using customizable moving averages expanded by a volatility multiplier directly on the main price chart. It identifies dynamic support and resistance liquidity zones from swing high and low pivots, extendi

Indicator v6 TrendSupport & resistance
Updated 3 months ago · MPL-2.0 GitHub repository of Apex Trend & Liquidity Master

More SMC / ICT scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers