• Get $40 off VIP by signing up for a free account! Sign Up

Market Structure Trailing Stop [LuxAlgo] for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
1qDmYQs.png

https://www.tradingview.com/script/c4Z9xThG-Market-Structure-Trailing-Stop-LuxAlgo/
Author Message - Conversion not Typical -

This script returns trailing stops on the occurrence of market structure (CHoCH/BOS labeling). Trailing stops are adjusted based on trailing maximums/minimums with the option for users to be able to control how quickly a trailing stop can converge toward the price.

Added MTF and some bug fix:

CODE:

CSS:
#// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4
#// © LuxAlgo
#indicator("Market Structure Trailing Stop [LuxAlgo]", overlay = true, max_lines_count = 500)
# Converted by Sam4Cok@Samer800    - 04/2023
# Updated by Sam4Cok@Samer800    - 07/2023 - MTF option added
# bug fix by Sam4Cok@Samer800    - 03/2024

input useChartTimeframe = {Default "Yes", "No"};
input manualTimeframe   = AggregationPeriod.FIFTEEN_MIN;
input PivotLookback  = 14;                  # 'Pivot Lookback')
input IncrementFactorPercent = 100;         # 'Increment Factor %', minval = 0)
input ResetStopOn = {default CHoCH, All};   # 'Reset Stop On'
input ShowStructures = yes;                # "Show Structures"
input showLabel      = yes;

def na = Double.NaN;
def ohlc = ohlc4;
def n = CompoundValue(1, AbsValue(BarNumber()), 0);
def CHoCH = ResetStopOn == ResetStopOn.CHoCH;
def c; def h; def l;
Switch (useChartTimeframe) {
Case "No" :
    c = close(Period=manualTimeframe);
    h = high(Period=manualTimeframe);
    l = low(Period=manualTimeframe);
Default :
    c = close;
    h = high;
    l = low;
}
def hh = highest(h, PivotLookback);
def ll = lowest(l, PivotLookback);
#-- Color
DefineGlobalColor("up", CreateColor(0, 137, 123));
DefineGlobalColor("dn", CreateColor(255, 82, 82));
# Function
script Pivots {
    input series    = hl2;
    input leftBars  = 10;
    input rightBars = 10;
    input isHigh = yes;
    def na = Double.NaN;
    def HH = series == Highest(series, leftBars + 1);
    def LL = series == Lowest(series, leftBars + 1);
    def pivotRange = (leftBars + rightBars + 1);
    def leftEdgeValue = if series[pivotRange] == 0 then na else series[pivotRange];
    def pvtCond = !IsNaN(series) and leftBars > 0 and rightBars > 0 and !IsNaN(leftEdgeValue);
    def barIndexH = if pvtCond then
                    fold i = 1 to rightBars + 1 with p=1 while p do
                    series > GetValue(series, - i) else na;
    def barIndexL = if pvtCond then
                    fold j = 1 to rightBars + 1 with q=1 while q do
                    series < GetValue(series, - j) else na;
    def PivotPoint;
    if isHigh {
        PivotPoint = if HH and barIndexH then series else na;
    } else {
        PivotPoint = if LL and barIndexL then series else na;
    }
    plot pvt = PivotPoint;
}
#//Detect pivots and get coordinates
def ph = Pivots(h, PivotLookback, PivotLookback, yes)[PivotLookback];
def pl = Pivots(l, PivotLookback, PivotLookback, no)[PivotLookback];

def ph_y;
def ph_x;
def ph_cross;
def phcross;
def pl_y;
def pl_x;
def pl_cross;
def plcross;
if !IsNaN(ph) {
    ph_y = ph;
    ph_x = n - PivotLookback;
    ph_cross = no;
} else {
    ph_y = if ph_y[1]==0 then hh else ph_y[1];
    ph_x = if ph_x[1]<1 then 1 else ph_x[1];
    ph_cross = if isNaN(phcross[1]) then 0 else phcross[1];
    ;
}
if !IsNaN(pl) {
    pl_y = pl;
    pl_x = n - PivotLookback;
    pl_cross = no;
} else {
    pl_y = if pl_y[1]==0 then ll else pl_y[1];
    pl_x = if pl_x[1]<1 then 1 else pl_x[1];
    pl_cross = if isNaN(plcross[1]) then 0 else plcross[1];
}
def foldMax = if (n - ph_x) > 0 then (n - ph_x) else 1;
def foldMin = if (n - pl_x) > 0 then (n - pl_x) else 1;
def ms;
def os;
def top;
def btm;
def CoHY;
def CoHX;
def CoLY;
def CoLX;
def BoHY;
def BoHX;
def BoLY;
def BoLX;
#//Bullish structures
if c > ph_y and !ph_cross {
    ms = if CHoCH then if os[1] == -1 then 1 else 0 else 1;
    phcross = yes;
    plcross = pl_cross;
    top = top[1];
    btm = fold i = 0 to foldMax with p = l do
          Min(GetValue(l, i), p);
    CoHY = if ShowStructures then if os[1] ==-1 then n    else CoHY[1] else na;
    CoHX = if ShowStructures then if os[1] ==-1 then ph_x else CoHX[1] else na;
    BoHY = if ShowStructures then if os[1] == 1 then n    else BoHY[1] else na;
    BoHX = if ShowStructures then if os[1] == 1 then ph_x else BoHX[1] else na;
    os = 1;
    CoLY = CoLY[1];
    CoLX = CoLX[1];
    BoLY = BoLY[1];
    BoLX = BoLX[1];
#//Bearish structures
} else if c < pl_y and !pl_cross {
    ms = if CHoCH then if os[1] == 1 then -1 else 0 else -1;
    phcross = ph_cross;
    plcross = yes;
    top = fold j = 0 to foldMin with q = h do
          Max(GetValue(h, j), q);
    btm = btm[1];
    CoLY = if ShowStructures then if os[1] == 1 then n    else CoLY[1] else na;
    CoLX = if ShowStructures then if os[1] == 1 then pl_x else CoLX[1] else na;
    BoLY = if ShowStructures then if os[1] ==-1 then n    else BoLY[1] else na;
    BoLX = if ShowStructures then if os[1] ==-1 then pl_x else BoLX[1] else na;
    os = -1;
    CoHY = CoHY[1];
    CoHX = CoHX[1];
    BoHY = BoHY[1];
    BoHX = BoHX[1];
} else {
    ms = 0;
    os = os[1];
    phcross = ph_cross;
    plcross = pl_cross;
    top = if top[1]==0 then hh else top[1];
    btm = if btm[1]==0 then ll else btm[1];
    CoHY = CoHY[1];
    CoHX = CoHX[1];
    CoLY = CoLY[1];
    CoLX = CoLX[1];
    BoHY = BoHY[1];
    BoHX = BoHX[1];
    BoLY = BoLY[1];
    BoLX = BoLX[1];
}
#//Trailing stop
#//Trailing max/min

def max = if ms == 1 then c else Max(c, max[1]);
def min = if ms ==-1 then c else Min(c, if(min[1]==0, c, min[1]));
#//Trailing stop
def ts = if ms == 1 then btm else
         if ms ==-1 then top else
         if os == 1 then if(ts[1]==0,ll,ts[1]) + (max - max[1]) * IncrementFactorPercent / 100 else
                         if(ts[1]==0,hh,ts[1]) + (min - min[1]) * IncrementFactorPercent / 100;
def css = if ms then na else if os == 1 then 1 else -1;
def css_area = if (c - ts) * os < 0 then 0 else css;

plot TrailingStop = if !isNaN(css) and ts then ts else na;
TrailingStop.AssignValueColor(if os == 1 then GlobalColor("up") else GlobalColor("dn"));

AddCloud(if css_area>0 then ohlc else na, TrailingStop, Color.DARK_GREEN);
AddCloud(if css_area<0 then TrailingStop else na, ohlc, Color.DARK_RED);
AddCloud(if css_area==0 then TrailingStop else na, ohlc, Color.DARK_GRAY, Color.DARK_GRAY);

def CoHSta = if n == highestAll(CoHX) then h else CoHSta[1];
def CoLSta = if n == highestAll(CoLX) then l else CoLSta[1];
def BoHSta = if n == highestAll(BoHX) then h else BoHSta[1];
def BoLSta = if n == highestAll(BoLX) then l else BoLSta[1];

def CoHEnd = n < highestAll(CoHY);
def CoLEnd = n < highestAll(CoLY);
def BoHEnd = n < highestAll(BoHY);
def BoLEnd = n < highestAll(BoLY);

def CoPhEnd = if !CoHEnd and CoHEnd[1] then n else CoPhEnd[1];
def CoPlEnd = if !CoLEnd and CoLEnd[1] then n else CoPlEnd[1];
def BoPhEnd = if !BoHEnd and BoHEnd[1] then n else BoPhEnd[1];
def BoPlEnd = if !BoLEnd and BoLEnd[1] then n else BoPlEnd[1];

plot bullCoCh = if CoHSta and CoHEnd then CoHSta else na;
plot bearCoCh = if CoLSta and CoLEnd then CoLSta else na;
plot bullBos = if BoHSta and BoHEnd then BoHSta else na;
plot bearBos = if BoLSta and BoLEnd then BoLSta else na;

bullBos.SetPaintingStrategy(PaintingStrategy.POINTS);
bearBos.SetPaintingStrategy(PaintingStrategy.POINTS);
bullCoCh.SetStyle(Curve.SHORT_DASH);
bearCoCh.SetStyle(Curve.SHORT_DASH);
bullCoCh.SetDefaultColor(Color.CYAN);
bearCoCh.SetDefaultColor(Color.MAGENTA);
bullBos.SetDefaultColor(Color.LIGHT_GREEN);
bearBos.SetDefaultColor(Color.PINK);


def coHLab = floor((CoHX + CoPhEnd)/2);
def coLLab = floor((CoLX + CoPlEnd)/2);
def boHLab = floor((BoHX + BoPhEnd)/2);
def boLLab = floor((BoLX + BoPlEnd)/2);

AddChartBubble(showLabel and n == highestAll(coHLab), bullCoCh,"ChoCh", Color.CYAN);
AddChartBubble(showLabel and n == highestAll(coLLab), bearCoCh,"ChoCh", Color.MAGENTA, no);
AddChartBubble(showLabel and n == highestAll(boHLab), bullBos,"BOS", Color.LIGHT_GREEN);
AddChartBubble(showLabel and n == highestAll(boLLab), bearBos,"BOS", Color.PINK, no);


#-- END of CODE

CODE:
CSS:
#// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) #https://www.tradingview.com/v/c4Z9xThG/
#// © LuxAlgo
#indicator("Market Structure Trailing Stop [LuxAlgo]"
# Converted by Sam4Cok@Samer800    - 04/2023

input PivotLookback   = 14;                # 'Pivot Lookback'
input IncrementFactor = 100;               # 'Increment Factor %'
input ResetStopOn     = {default "CHoCH", "All"};    # 'Reset Stop On'
input showStructures  = yes;               # "Show Structures"

#//Style
DefineGlobalColor("bull" , CreateColor(0,137,123));
DefineGlobalColor("bear" , CreateColor(255,82,82));
DefineGlobalColor("dbull" , CreateColor(0, 61, 54));
DefineGlobalColor("dbear" , CreateColor(82, 0, 0));
DefineGlobalColor("ret"  , Color.GRAY);

def na = Double.NaN;
def last = isNaN(close);
def CHoCH = ResetStopOn == ResetStopOn."CHoCH";

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;     # default high or low pivot designation, -1 low, +1 high
    input lbL  = 14;   # default Pivot Lookback Left
    input lbR  = 14;   # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
def n = floor(AbsValue(CompoundValue(1, BarNumber(), 1)));
def ph =  findpivots(high, 1, PivotLookback, PivotLookback);
def pl =  findpivots(low, -1, PivotLookback, PivotLookback);

def ph_y;
def ph_x;
def ph_cross;
def ph_cross_;
def os;
def bullLine;
def ms;
def btm;
def pl_y;
def pl_x;
def pl_cross;
def pl_cross_;
def bearLine;
def top;
if !IsNaN(ph) {
    ph_y = ph;
    ph_x = n;
    ph_cross = no;
} else {
    ph_y = if ph_y[1]==0 then highest(high, PivotLookback) else ph_y[1];
    ph_x = if ph_x[1]<=1 then 1 else ph_x[1];
    ph_cross = ph_cross_[1];
}
if !IsNaN(pl) {
    pl_y = pl;
    pl_x = n;
    pl_cross = no;
} else {
    pl_y = if pl_y[1]==0 then lowest(low, PivotLookback) else pl_y[1];
    pl_x = if pl_x[1]<=1 then 1 else pl_x[1];
    pl_cross = pl_cross_[1];
}
#//-----------------------------------------------------------------------------}
#//Bullish structures
#//-----------------------------------------------------------------------------{
if close > ph_y and !ph_cross[1] {
    ms = if CHoCH then if os[1] == -1 then 1 else 0 else 1;
    ph_cross_ = yes;
    bullLine = if showStructures then ph_y else na;
    btm = fold i = 0 to (n - ph_x) with p=low do
          Min(GetValue(low, i), p);
    top = if top[1]==0 then high else top[1];
    os = 1;
    pl_cross_ = pl_cross;
    bearLine = bearLine[1];
} else
if close < pl_y and !pl_cross[1] {
    ms = if CHoCH then if os[1] == 1 then -1 else 0 else -1;
    bearLine = if showStructures then pl_y else na;
    pl_cross_ = yes;
    ph_cross_ = ph_cross;
    bullLine = bullLine[1];
    btm = if btm[1]==0 then low else btm[1];
    top = fold i1 = 0 to (n - pl_x) with p1=high do
          Max(GetValue(high, i1), p1);
    os = -1;
} else {
    ms = if isNaN(ms[1]) then 0 else
         if CHoCH then ms[1] else
         if close > ph_y and !ph_cross[1] then  1 else
         if close < pl_y and !pl_cross[1] then -1 else 0;
    pl_cross_ = pl_cross[1];
    ph_cross_ = ph_cross[1];
    bullLine = bullLine[1];
    bearLine = bearLine[1];
    btm = btm[1];
    top = top[1];
    os = os[1];
}
#//Trailing stop
#//Trailing max/min
def max; def min;
if ms == 1 {
    max = close;
    min = if min[1]==0 then average(close,PivotLookback) else min[1];
    } else
if ms == -1 {
    max = if max[1]==0 then average(close,PivotLookback) else max[1];
    min = close;
    } else {
    max = max(close, if max[1]==0 then average(close,PivotLookback) else max[1]);
    min = min(close, if min[1]==0 then average(close,PivotLookback) else min[1]);
}

#//Trailing stop
def ts = if ms == 1  then btm else
         if ms == -1 then top else
         if os == 1 then if(ts[1]==0, close, ts[1]) + (max - max[1]) * IncrementFactor / 100 else
                         if(ts[1]==0, close, ts[1]) + (min - min[1]) * IncrementFactor / 100;

#//Plots
def css = if ms then 0 else
          if os == 1 then 1 else -1;

def plot_price = ohlc4;
plot plot_ts    = if css==0 then na else ts;    # 'Trailing Stop'
plot_ts.AssignValueColor(if css>0 then GlobalColor("bull") else GlobalColor("bear"));

plot CHoCHup = if bullLine==0 or last or os==-1 then na else bullLine;
plot CHoCHdn = if bearLine==0 or last or os== 1 then na else bearLine;
CHoCHup.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHdn.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHup.SetDefaultColor(Color.CYAN);
CHoCHdn.SetDefaultColor(Color.MAGENTA);

plot CHoCHup_ = if bullLine==0 or last or os!=-1 then na else bullLine;
plot CHoCHdn_ = if bearLine==0 or last or os!= 1 then na else bearLine;
CHoCHup_.SetStyle(Curve.LONG_DASH);
CHoCHdn_.SetStyle(Curve.LONG_DASH);
CHoCHup_.SetDefaultColor(Color.CYAN);
CHoCHdn_.SetDefaultColor(Color.MAGENTA);

def css_area = if (close - ts) * os < 0 then 3 else css;

AddCloud(if css_area==1 then plot_price else na,plot_ts,  GlobalColor("dbull"));
AddCloud(if css_area==-1 then plot_ts else na,plot_price, GlobalColor("dbear"));
AddCloud(if css_area==3 then plot_ts else na,plot_price,  GlobalColor("ret"), GlobalColor("ret"));


#--- END of CODE
 
Last edited:
1qDmYQs.png


Author Message - Conversion not Typical -

This script returns trailing stops on the occurrence of market structure (CHoCH/BOS labeling). Trailing stops are adjusted based on trailing maximums/minimums with the option for users to be able to control how quickly a trailing stop can converge toward the price.

CODE:
CSS:
#// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) #https://www.tradingview.com/v/c4Z9xThG/
#// © LuxAlgo
#indicator("Market Structure Trailing Stop [LuxAlgo]"
# Converted by Sam4Cok@Samer800    - 04/2023

input PivotLookback   = 14;                # 'Pivot Lookback'
input IncrementFactor = 100;               # 'Increment Factor %'
input ResetStopOn     = {default "CHoCH", "All"};    # 'Reset Stop On'
input showStructures  = yes;               # "Show Structures"

#//Style
DefineGlobalColor("bull" , CreateColor(0,137,123));
DefineGlobalColor("bear" , CreateColor(255,82,82));
DefineGlobalColor("dbull" , CreateColor(0, 61, 54));
DefineGlobalColor("dbear" , CreateColor(82, 0, 0));
DefineGlobalColor("ret"  , Color.GRAY);

def na = Double.NaN;
def last = isNaN(close);
def CHoCH = ResetStopOn == ResetStopOn."CHoCH";

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;     # default high or low pivot designation, -1 low, +1 high
    input lbL  = 14;   # default Pivot Lookback Left
    input lbR  = 14;   # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
def n = floor(AbsValue(CompoundValue(1, BarNumber(), 1)));
def ph =  findpivots(high, 1, PivotLookback, PivotLookback);
def pl =  findpivots(low, -1, PivotLookback, PivotLookback);

def ph_y;
def ph_x;
def ph_cross;
def ph_cross_;
def os;
def bullLine;
def ms;
def btm;
def pl_y;
def pl_x;
def pl_cross;
def pl_cross_;
def bearLine;
def top;
if !IsNaN(ph) {
    ph_y = ph;
    ph_x = n;
    ph_cross = no;
} else {
    ph_y = if ph_y[1]==0 then highest(high, PivotLookback) else ph_y[1];
    ph_x = if ph_x[1]<=1 then 1 else ph_x[1];
    ph_cross = ph_cross_[1];
}
if !IsNaN(pl) {
    pl_y = pl;
    pl_x = n;
    pl_cross = no;
} else {
    pl_y = if pl_y[1]==0 then lowest(low, PivotLookback) else pl_y[1];
    pl_x = if pl_x[1]<=1 then 1 else pl_x[1];
    pl_cross = pl_cross_[1];
}
#//-----------------------------------------------------------------------------}
#//Bullish structures
#//-----------------------------------------------------------------------------{
if close > ph_y and !ph_cross[1] {
    ms = if CHoCH then if os[1] == -1 then 1 else 0 else 1;
    ph_cross_ = yes;
    bullLine = if showStructures then ph_y else na;
    btm = fold i = 0 to (n - ph_x) with p=low do
          Min(GetValue(low, i), p);
    top = if top[1]==0 then high else top[1];
    os = 1;
    pl_cross_ = pl_cross;
    bearLine = bearLine[1];
} else
if close < pl_y and !pl_cross[1] {
    ms = if CHoCH then if os[1] == 1 then -1 else 0 else -1;
    bearLine = if showStructures then pl_y else na;
    pl_cross_ = yes;
    ph_cross_ = ph_cross;
    bullLine = bullLine[1];
    btm = if btm[1]==0 then low else btm[1];
    top = fold i1 = 0 to (n - pl_x) with p1=high do
          Max(GetValue(high, i1), p1);
    os = -1;
} else {
    ms = if isNaN(ms[1]) then 0 else
         if CHoCH then ms[1] else
         if close > ph_y and !ph_cross[1] then  1 else
         if close < pl_y and !pl_cross[1] then -1 else 0;
    pl_cross_ = pl_cross[1];
    ph_cross_ = ph_cross[1];
    bullLine = bullLine[1];
    bearLine = bearLine[1];
    btm = btm[1];
    top = top[1];
    os = os[1];
}
#//Trailing stop
#//Trailing max/min
def max; def min;
if ms == 1 {
    max = close;
    min = if min[1]==0 then average(close,PivotLookback) else min[1];
    } else
if ms == -1 {
    max = if max[1]==0 then average(close,PivotLookback) else max[1];
    min = close;
    } else {
    max = max(close, if max[1]==0 then average(close,PivotLookback) else max[1]);
    min = min(close, if min[1]==0 then average(close,PivotLookback) else min[1]);
}

#//Trailing stop
def ts = if ms == 1  then btm else
         if ms == -1 then top else
         if os == 1 then if(ts[1]==0, close, ts[1]) + (max - max[1]) * IncrementFactor / 100 else
                         if(ts[1]==0, close, ts[1]) + (min - min[1]) * IncrementFactor / 100;

#//Plots
def css = if ms then 0 else
          if os == 1 then 1 else -1;

def plot_price = ohlc4;
plot plot_ts    = if css==0 then na else ts;    # 'Trailing Stop'
plot_ts.AssignValueColor(if css>0 then GlobalColor("bull") else GlobalColor("bear"));

plot CHoCHup = if bullLine==0 or last or os==-1 then na else bullLine;
plot CHoCHdn = if bearLine==0 or last or os== 1 then na else bearLine;
CHoCHup.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHdn.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHup.SetDefaultColor(Color.CYAN);
CHoCHdn.SetDefaultColor(Color.MAGENTA);

plot CHoCHup_ = if bullLine==0 or last or os!=-1 then na else bullLine;
plot CHoCHdn_ = if bearLine==0 or last or os!= 1 then na else bearLine;
CHoCHup_.SetStyle(Curve.LONG_DASH);
CHoCHdn_.SetStyle(Curve.LONG_DASH);
CHoCHup_.SetDefaultColor(Color.CYAN);
CHoCHdn_.SetDefaultColor(Color.MAGENTA);

def css_area = if (close - ts) * os < 0 then 3 else css;

AddCloud(if css_area==1 then plot_price else na,plot_ts,  GlobalColor("dbull"));
AddCloud(if css_area==-1 then plot_ts else na,plot_price, GlobalColor("dbear"));
AddCloud(if css_area==3 then plot_ts else na,plot_price,  GlobalColor("ret"), GlobalColor("ret"));


#--- END of CODE
could i use it for 1 min chart ?
 
could i use it for 1 min chart ?
The script will run without errors on a 1min chart.
It might not be very helpful.
1min charts tend to have too much noise to settle into trending zones.
 
Last edited:
Thank you so much @samer800, i trade with market structure on tradingview and this helps me a lot on TOS.

Do you think you would be able to convert it in MTF indicador? just for studying purpouses, it will be great.

Thanks anyway ;););)
 
Thank you so much @samer800, i trade with market structure on tradingview and this helps me a lot on TOS.

Do you think you would be able to convert it in MTF indicador? just for studying purpouses, it will be great.

Thanks anyway ;););)
pls test it.

CSS:
#// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) #https://www.tradingview.com/v/c4Z9xThG/
#// © LuxAlgo
#indicator("Market Structure Trailing Stop [LuxAlgo]"
# Converted by Sam4Cok@Samer800    - 04/2023
# Updated by Sam4Cok@Samer800    - 07/2023 - MTF option added
input useChartTimeframe = {Default "Yes", "No"};
input manualTimeframe   = AggregationPeriod.FIFTEEN_MIN;
input PivotLookback   = 14;                # 'Pivot Lookback'
input IncrementFactor = 100;               # 'Increment Factor %'
input ResetStopOn     = {default "CHoCH", "All"};    # 'Reset Stop On'
input showStructures  = yes;               # "Show Structures"

def na = Double.NaN;
def last = isNaN(close);
def CHoCH = ResetStopOn == ResetStopOn."CHoCH";

def c; def h; def l;
Switch (useChartTimeframe) {
Case "Yes" :
    c = close;
    h = high;
    l = low;
Case "No" :
    c = close(Period=manualTimeframe);
    h = high(Period=manualTimeframe);
    l = low(Period=manualTimeframe);
}
#//Style
DefineGlobalColor("bull" , CreateColor(0,137,123));
DefineGlobalColor("bear" , CreateColor(255,82,82));
DefineGlobalColor("dbull" , CreateColor(0, 61, 54));
DefineGlobalColor("dbear" , CreateColor(82, 0, 0));
DefineGlobalColor("ret"  , Color.GRAY);

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;     # default high or low pivot designation, -1 low, +1 high
    input lbL  = 14;   # default Pivot Lookback Left
    input lbR  = 14;   # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
def n = floor(AbsValue(CompoundValue(1, BarNumber(), 1)));
def ph =  findpivots(h, 1, PivotLookback, PivotLookback);
def pl =  findpivots(l, -1, PivotLookback, PivotLookback);

def ph_y;
def ph_x;
def ph_cross;
def ph_cross_;
def os;
def bullLine;
def ms;
def btm;
def pl_y;
def pl_x;
def pl_cross;
def pl_cross_;
def bearLine;
def top;
if !IsNaN(ph) {
    ph_y = ph;
    ph_x = n;
    ph_cross = no;
} else {
    ph_y = if ph_y[1]==0 then highest(h, PivotLookback) else ph_y[1];
    ph_x = if ph_x[1]<=1 then 1 else ph_x[1];
    ph_cross = ph_cross_[1];
}
if !IsNaN(pl) {
    pl_y = pl;
    pl_x = n;
    pl_cross = no;
} else {
    pl_y = if pl_y[1]==0 then lowest(l, PivotLookback) else pl_y[1];
    pl_x = if pl_x[1]<=1 then 1 else pl_x[1];
    pl_cross = pl_cross_[1];
}
#//-----------------------------------------------------------------------------}
#//Bullish structures
#//-----------------------------------------------------------------------------{
if c > ph_y and !ph_cross[1] {
    ms = if CHoCH then if os[1] == -1 then 1 else 0 else 1;
    ph_cross_ = yes;
    bullLine = if showStructures then ph_y else na;
    btm = fold i = 0 to (n - ph_x) with p=l do
          Min(GetValue(l, i), p);
    top = if top[1]==0 then h else top[1];
    os = 1;
    pl_cross_ = pl_cross;
    bearLine = bearLine[1];
} else
if c < pl_y and !pl_cross[1] {
    ms = if CHoCH then if os[1] == 1 then -1 else 0 else -1;
    bearLine = if showStructures then pl_y else na;
    pl_cross_ = yes;
    ph_cross_ = ph_cross;
    bullLine = bullLine[1];
    btm = if btm[1]==0 then l else btm[1];
    top = fold i1 = 0 to (n - pl_x) with p1=h do
          Max(GetValue(h, i1), p1);
    os = -1;
} else {
    ms = if isNaN(ms[1]) then 0 else
         if CHoCH then ms[1] else
         if c > ph_y and !ph_cross[1] then  1 else
         if c < pl_y and !pl_cross[1] then -1 else 0;
    pl_cross_ = pl_cross[1];
    ph_cross_ = ph_cross[1];
    bullLine = bullLine[1];
    bearLine = bearLine[1];
    btm = btm[1];
    top = top[1];
    os = os[1];
}
#//Trailing stop
#//Trailing max/min
def max; def min;
if ms == 1 {
    max = c;
    min = if min[1]==0 then average(c,PivotLookback) else min[1];
    } else
if ms == -1 {
    max = if max[1]==0 then average(c,PivotLookback) else max[1];
    min = c;
    } else {
    max = max(c, if max[1]==0 then average(c,PivotLookback) else max[1]);
    min = min(c, if min[1]==0 then average(c,PivotLookback) else min[1]);
}

#//Trailing stop
def ts = if ms == 1  then btm else
         if ms == -1 then top else
         if os == 1 then if(ts[1]==0, c, ts[1]) + (max - max[1]) * IncrementFactor / 100 else
                         if(ts[1]==0, c, ts[1]) + (min - min[1]) * IncrementFactor / 100;

#//Plots
def css = if ms then 0 else
          if os == 1 then 1 else -1;

def plot_price = ohlc4;
plot plot_ts    = if css==0 then na else ts;    # 'Trailing Stop'
plot_ts.AssignValueColor(if css>0 then GlobalColor("bull") else GlobalColor("bear"));

plot CHoCHup = if bullLine==0 or last or os==-1 then na else bullLine;
plot CHoCHdn = if bearLine==0 or last or os== 1 then na else bearLine;
CHoCHup.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHdn.SetPaintingStrategy(PaintingStrategy.DASHES);
CHoCHup.SetDefaultColor(Color.CYAN);
CHoCHdn.SetDefaultColor(Color.MAGENTA);

plot CHoCHup_ = if bullLine==0 or last or os!=-1 then na else bullLine;
plot CHoCHdn_ = if bearLine==0 or last or os!= 1 then na else bearLine;
CHoCHup_.SetStyle(Curve.LONG_DASH);
CHoCHdn_.SetStyle(Curve.LONG_DASH);
CHoCHup_.SetDefaultColor(Color.CYAN);
CHoCHdn_.SetDefaultColor(Color.MAGENTA);

def css_area = if (c - ts) * os < 0 then 3 else css;

AddCloud(if css_area==1 then plot_price else na,plot_ts,  GlobalColor("dbull"));
AddCloud(if css_area==-1 then plot_ts else na,plot_price, GlobalColor("dbear"));
AddCloud(if css_area==3 then plot_ts else na,plot_price,  GlobalColor("ret"), GlobalColor("ret"));


#--- END of CODE
 
I have been following this script. Pretty amazing. Just needed some clarification: The solid blue vs dash blue lines and solid pink vs dash pink lines. Basically, not sure what is CHoCHup and CHoCHup_? Please provide some details that will be helpful. Also, does it show the first pull back at a major high or low level which will be a CHoCH and not an inducement?

Confused for ChoCHup vs CHoCHup_. Also, looks like BOS is deonated by small dash line.
 
I have been following this script. Pretty amazing. Just needed some clarification: The solid blue vs dash blue lines and solid pink vs dash pink lines. Basically, not sure what is CHoCHup and CHoCHup_? Please provide some details that will be helpful. Also, does it show the first pull back at a major high or low level which will be a CHoCH and not an inducement?

Confused for ChoCHup vs CHoCHup_. Also, looks like BOS is deonated by small dash line.

long dashed lines just an extension of the CHoCh
.
 
Could you explain how you use it ?
What triggers exit long or short?

This is a Market Structure indicator.
Market Structure, in its simplest definition, is an outline of the instrument; defining how the instrument generally trades.

To define market structure, you can use pivots, zigzags, range/channels/bands, or in this case, a trailing stop.

When you have defined your market structure, you can now look for Changes in Character (CHoCH).
A "CHoCH" signals a change in the direction of price movement. It marks a shift in the trend after price forms certain patterns.

When a bullish trend shifts, a CHoCH happens as a low is broken, and in a bearish trend, it occurs as a high is broken.

Important:
CHoCH (Change of Character) signals shouldn't be the sole basis for making trades. These signals are like a warning sign that hints at a potential change in the stock's direction.

CHoCH signals can pop up in different places on stock charts – sometimes it's just there without much impact. So, it's crucial to consider other factors alongside CHoCH signals. Use Market Structure and your other indicators to get the bigger picture; to determine which CHoCH signals are more likely to be important and influence your trading decisions.

Hope this helps.
 
Last edited:
Could you explain how you use it ?
What triggers exit long or short?
You can basically use it to have a clear picture of the trend in any timeframe you want, then u can enter with the trend, either on a retracement or a continuation pattern.
 
You can basically use it to have a clear picture of the trend in any timeframe you want, then u can enter with the trend, either on a retracement or a continuation pattern.
Thanks, I was mostly interested in using it in a script as a "filtered" conditional sell stop.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
444 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top