ATR-Based Volatility Stop Script not working

abbasia

New member
Hello everyone,
I have this ATR-based volatility stop script which is the modified version of TD. The script works, but I'm trying to make a small change, so it ONLY shows the current/active state as opposed to all the historical ones. I like my charts clean. Here is the two lines added to the old code. When I add the changes, it doesn'plot the TrailingStop anymore. Can someone help? Thanks a million.

------------ Here is the code the works --------
## Volatility Trailing Stop
## Version 1.1
## By Steve Coombs
## This ATR Trailing Stop is calculated using the Highest Close in an uptrend or
## the Lowest Close in a downtrend, rather than just the Close that is used
## in the standard TOS ATRTrailing Stop
#input StopLabel = yes; #ATRStop Label is Stop value from yesterdays ATR calculation
input ATRPeriod = 8;
input ATRFactor = 3.0;
input firstTrade = {default long, short};
input averageType = AverageType.EXPONENTIAL;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def trueRange = TrueRange(high, close, low);
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
def mclose;
switch (state[1]) {
case init:
if (!IsNaN(loss)) {
switch (firstTrade) {
case long:
state = state.long;
mclose = close;
trail = close - loss;
case short:
state = state.short;
mclose = close;
trail = close + loss;
}
} else {
state = state.init;
trail = Double.NaN;
mclose = Double.NaN;
}
case long:
if (close > trail[1]) {
state = state.long;
mclose = Max(mclose[1], close);
trail = Max (trail[1], mclose - loss);
} else {
state = state.short;
mclose = close;
trail = mclose + loss;
}
case short:
if (close < trail[1]) {
state = state.short;
mclose = Min(mclose[1], close);
trail = Min(trail[1], mclose + loss);
} else {
state = state.long;
mclose = close + 0;
trail = mclose - loss;
}
}

#AddLabel(StopLabel, "ATR Stop =" + Round(trail[1], 2), color = Color.BLUE);
plot TrailingStop = trail;

TrailingStop.SetPaintingStrategy(PaintingStrategy.POINTS);
TrailingStop.SetLineWeight(lineWeight = 3);
TrailingStop.DefineColor("Buy", GetColor(5));
TrailingStop.DefineColor("Sell", GetColor(1));
TrailingStop.AssignValueColor(if state == state.long
then TrailingStop.Color("Sell")
else TrailingStop.Color("Buy"));

# Alerts:
def VStopBull = state[1] == state.short and state == state.long;
def VStopBear = state[1] == state.long and state == state.short;

plot VStopLong = VStopBull AND (close is greater than TrailingStop);
plot VStopShort = VStopBear AND (close is less than TrailingStop);

# BLOCK CODE BELOW
input UseAlerts = {false, default true};
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
Alert(VStopBull AND UseAlerts, "VStop Transition Bull", Alert.BAR, Sound.Ding);
Alert(VStopBear AND UseAlerts,"VStop Transition Bear", Alert.BAR, Sound.Ding);

----------------------------------------------------
When I add this, the TrailingStop doesn't show.

def newState = HighestAll(if state <> state[1] then BarNumber() else 0);
plot TrailingStop = if BarNumber() < newState then Double.NaN else trail;
 
Solution
Unfortunately, it didn't. Same problem as my original code with the state machine. It doesn't plot TrailingStop at all.

this works , plots just the most recent stop points

i had to fix this line in post6
,.. def maxcnt = highestall(bs_cnt);
it wasn't right. it found the highest barnumber, but not the one with prices.


Code:
# atr_stop_just_last_02

#https://usethinkscript.com/threads/atr-based-volatility-stop-script-not-working.12573/
#ATR-Based Volatility Stop Script not working

#input StopLabel = yes; #ATRStop Label is Stop value from yesterdays ATR calculation
input ATRPeriod = 8;
input ATRFactor = 3.0;
input firstTrade = {default long, short};
input averageType = AverageType.EXPONENTIAL;

Assert(ATRFactor > 0, "'atr...
Hello everyone,
I have this ATR-based volatility stop script which is the modified version of TD. The script works, but I'm trying to make a small change, so it ONLY shows the current/active state as opposed to all the historical ones. I like my charts clean. Here is the two lines added to the old code. When I add the changes, it doesn'plot the TrailingStop anymore. Can someone help? Thanks a million.

------------ Here is the code the works --------
## Volatility Trailing Stop
## Version 1.1
## By Steve Coombs
## This ATR Trailing Stop is calculated using the Highest Close in an uptrend or
## the Lowest Close in a downtrend, rather than just the Close that is used
## in the standard TOS ATRTrailing Stop
#input StopLabel = yes; #ATRStop Label is Stop value from yesterdays ATR calculation
input ATRPeriod = 8;
input ATRFactor = 3.0;
input firstTrade = {default long, short};
input averageType = AverageType.EXPONENTIAL;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def trueRange = TrueRange(high, close, low);
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
def mclose;
switch (state[1]) {
case init:
if (!IsNaN(loss)) {
switch (firstTrade) {
case long:
state = state.long;
mclose = close;
trail = close - loss;
case short:
state = state.short;
mclose = close;
trail = close + loss;
}
} else {
state = state.init;
trail = Double.NaN;
mclose = Double.NaN;
}
case long:
if (close > trail[1]) {
state = state.long;
mclose = Max(mclose[1], close);
trail = Max (trail[1], mclose - loss);
} else {
state = state.short;
mclose = close;
trail = mclose + loss;
}
case short:
if (close < trail[1]) {
state = state.short;
mclose = Min(mclose[1], close);
trail = Min(trail[1], mclose + loss);
} else {
state = state.long;
mclose = close + 0;
trail = mclose - loss;
}
}

#AddLabel(StopLabel, "ATR Stop =" + Round(trail[1], 2), color = Color.BLUE);
plot TrailingStop = trail;

TrailingStop.SetPaintingStrategy(PaintingStrategy.POINTS);
TrailingStop.SetLineWeight(lineWeight = 3);
TrailingStop.DefineColor("Buy", GetColor(5));
TrailingStop.DefineColor("Sell", GetColor(1));
TrailingStop.AssignValueColor(if state == state.long
then TrailingStop.Color("Sell")
else TrailingStop.Color("Buy"));

# Alerts:
def VStopBull = state[1] == state.short and state == state.long;
def VStopBear = state[1] == state.long and state == state.short;

plot VStopLong = VStopBull AND (close is greater than TrailingStop);
plot VStopShort = VStopBear AND (close is less than TrailingStop);

# BLOCK CODE BELOW
input UseAlerts = {false, default true};
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
Alert(VStopBull AND UseAlerts, "VStop Transition Bull", Alert.BAR, Sound.Ding);
Alert(VStopBear AND UseAlerts,"VStop Transition Bear", Alert.BAR, Sound.Ding);

----------------------------------------------------
When I add this, the TrailingStop doesn't show.

def newState = HighestAll(if state <> state[1] then BarNumber() else 0);
plot TrailingStop = if BarNumber() < newState then Double.NaN else trail;

i think you want just the last point to be plotted.
i think this will do that.

copy the code below into your code, just above your
plot TrailingStop = ... code line.

then disable your line, like this
# plot TrailingStop


Code:
# plot just the last point
input recent_bars = 1;
# x is true during the last y bars on chart
def x = (!isnan(close) and isnan(close[-recent_bars]));

plot TrailingStop = if x then trail else double.nan;
 
i think you want just the last point to be plotted.
i think this will do that.

copy the code below into your code, just above your
plot TrailingStop = ... code line.

then disable your line, like this
# plot TrailingStop


Code:
# plot just the last point
input recent_bars = 1;
# x is true during the last y bars on chart
def x = (!isnan(close) and isnan(close[-recent_bars]));

plot TrailingStop = if x then trail else double.nan;

That worked! Thanks so much. I hope it's not too much to ask but is it possible to make it plot the last state? By last state I mean the trailing stop dots moving from Red to Green? So only see the Green.
 
That worked! Thanks so much. I hope it's not too much to ask but is it possible to make it plot the last state? By last state I mean the trailing stop dots moving from Red to Green? So only see the Green.

that should be doable, but that will be more complicated, more so than i can type out on my cell. i'm moving my office around and will be a couple days till i get my computer set up.

my idea,
. make a counter that increments on the 1st bar of each color change.
. find max count of colors (on last bar)
..set a variable true during bars that = the max count.
..plot points when var is true
 
that should be doable, but that will be more complicated, more so than i can type out on my cell. i'm moving my office around and will be a couple days till i get my computer set up.

my idea,
. make a counter that increments on the 1st bar of each color change.
. find max count of colors (on last bar)
..set a variable true during bars that = the max count.
..plot points when var is true

Thanks for your reply. Let me give it a try. But you happened to come up with it sooner than I do; please share your new code. Thank you!
 
Thanks for your reply. Let me give it a try. But you happened to come up with it sooner than I do; please share your new code. Thank you!


had an idea and wrote it out. maybe this will work...

Code:
# make a counter that increments on the 1st bar of each buy/sell color change.
def bn = barnumber();
def bs_cnt = if bn == 1 then 1
else if state != state[1] then bs_cnt[1] + 1
else bs_cnt[1];

# find max count of colors
def maxcnt = highestall(bs_cnt);

# set a variable true during bars that = the max count.
def t = if bs_cnt == maxcnt then 1 else 0;

# plot points when var is true
plot TrailingStop = if t then trail else double.nan;
 
had an idea and wrote it out. maybe this will work...

Code:
# make a counter that increments on the 1st bar of each buy/sell color change.
def bn = barnumber();
def bs_cnt = if bn == 1 then 1
else if state != state[1] then bs_cnt[1] + 1
else bs_cnt[1];

# find max count of colors
def maxcnt = highestall(bs_cnt);

# set a variable true during bars that = the max count.
def t = if bs_cnt == maxcnt then 1 else 0;

# plot points when var is true
plot TrailingStop = if t then trail else double.nan;

Unfortunately, it didn't. Same problem as my original code with the state machine. It doesn't plot TrailingStop at all.
 
had an idea and wrote it out. maybe this will work...

Code:
# make a counter that increments on the 1st bar of each buy/sell color change.
def bn = barnumber();
def bs_cnt = if bn == 1 then 1
else if state != state[1] then bs_cnt[1] + 1
else bs_cnt[1];

# find max count of colors
def maxcnt = highestall(bs_cnt);

# set a variable true during bars that = the max count.
def t = if bs_cnt == maxcnt then 1 else 0;

# plot points when var is true
plot TrailingStop = if t then trail else double.nan;

Interestingly, it looks like someone did the same thing for PSAR. I mean it only plots the last state. We just have to do it for the ATR Volatility Stop. I tried to copy but still doesn't work. Something is missing...

https://usethinkscript.com/threads/...-labels-charts-for-thinkorswim.515/post-13981
 
Unfortunately, it didn't. Same problem as my original code with the state machine. It doesn't plot TrailingStop at all.

this works , plots just the most recent stop points

i had to fix this line in post6
,.. def maxcnt = highestall(bs_cnt);
it wasn't right. it found the highest barnumber, but not the one with prices.


Code:
# atr_stop_just_last_02

#https://usethinkscript.com/threads/atr-based-volatility-stop-script-not-working.12573/
#ATR-Based Volatility Stop Script not working

#input StopLabel = yes; #ATRStop Label is Stop value from yesterdays ATR calculation
input ATRPeriod = 8;
input ATRFactor = 3.0;
input firstTrade = {default long, short};
input averageType = AverageType.EXPONENTIAL;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def trueRange = TrueRange(high, close, low);
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
def mclose;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            mclose = close;
            trail = close - loss;
        case short:
            state = state.short;
            mclose = close;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
        mclose = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        mclose = Max(mclose[1], close);
        trail = Max (trail[1], mclose - loss);
    } else {
        state = state.short;
        mclose = close;
        trail = mclose + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        mclose = Min(mclose[1], close);
        trail = Min(trail[1], mclose + loss);
    } else {
        state = state.long;
        mclose = close + 0;
        trail = mclose - loss;
    }
}

#AddLabel(StopLabel, "ATR Stop =" + Round(trail[1], 2), color = Color.BLUE);

# make a counter that increments on the 1st bar of each buy/sell color change.
def bn = barnumber();
def bs_cnt = if bn == 1 then 1
else if state != state[1] then bs_cnt[1] + 1
else bs_cnt[1];

# find max count of colors
def maxcnt = HighestAll(if !isnan(close) then bs_cnt else 0);
# set a variable true during bars that = the max count.
def t = if bs_cnt == maxcnt then 1 else 0;
# plot points when var is true
plot TrailingStop = if t then trail else Double.NaN;
#plot TrailingStop = trail;

addchartbubble(0, low*0.99,
state + "\n" +
bs_cnt + "\n" +
maxcnt + "\n" +
t
, color.yellow, no);

TrailingStop.SetPaintingStrategy(PaintingStrategy.POINTS);
TrailingStop.SetLineWeight(lineWeight = 3);
TrailingStop.DefineColor("Buy", GetColor(5));
TrailingStop.DefineColor("Sell", GetColor(1));
TrailingStop.AssignValueColor(if state == state.long
then TrailingStop.Color("Sell")
else TrailingStop.Color("Buy"));

# Alerts:
def VStopBull = state[1] == state.short and state == state.long;
def VStopBear = state[1] == state.long and state == state.short;

def VStopLong = VStopBull and (close is greater than TrailingStop);
def VStopShort = VStopBear and (close is less than TrailingStop);

# BLOCK CODE BELOW
input UseAlerts = {false, default true};
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
Alert(VStopBull and UseAlerts, "VStop Transition Bull", Alert.BAR, Sound.Ding);
Alert(VStopBear and UseAlerts, "VStop Transition Bear", Alert.BAR, Sound.Ding);
#
 
Solution

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
406 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