## Trailing stop Thinkscript openly posted on Twitter
def a;
def b;
def z;
def c;
def l;
def s;
plot trail;
def lX = Lowest(low, 3);
def hX = Highest(high, 3);
def lM = Average(low, 3);
def hM = Average(high, 3);
if BarNumber() > 1 and a[1] == 1
{
b = Max(lX, b[1]);
z = if hM < b[1] and close < low[1]
then 1
else z[1];
a = if hM < b[1] and close < low[1]
then 0
else a[1];
c = if hM < b[1] and close < low[1]
then hX
else c[1];
}
else if a[1] == 0
{
c = Min(hX, c[1]);
z = if lM > c[1] and close > high[1]
then 0
else z[1];
a = if lM > c[1] and close > high[1]
then 1
else a[1];
b = if lM > c[1] and close > high[1]
then lX
else b[1];
}
else
{
b = b[1];
z = z[1];
a = a[1];
c = c[1];
}
if z == 0
{
l = if z[1] <> 0
then s[1]
else Max(b[1], l[1]);
s = 0;
}
else if z[1] <> 1
{
s = l[1];
l = 0;
}
else if z == 1
{
s = Min(c, s[1]);
l = l[1];
}
else
{
l = l[1];
s = s[1];
}
if l > 0
{
trail = l;
}
else
{
trail = s;
}
trail.SetDefaultColor(createcolor(250,150,100));
trail.SetLineWeight(1);
trail.hidebubble();
## Code to paint price bars and trailing stop
def SMA1 = Average(OHLC4, 8);
def SMA2 = Average(OHLC4, 20);
def avgSMA = (SMA1 + SMA2) / 2;
trail.assignvaluecolor(if OHLC4 > avgSMA then Color.GREEN else if OHLC4 < avgSMA
then Color.RED else color.black);
assignpricecolor(if OHLC4 > avgSMA then Color.GREEN else if OHLC4 < avgSMA then
Color.RED else color.black);