ToS ATR Trailing Stop in ThinkOrSwim

bigpemby

New member
Not sure if you are meaning to add a study alert or something else. This particular study does not show up to be selectable when trying to setup a study alert. I also would like to be able SCAN for this condition which will require a custom scan script I am afraid.
 

wtf_dude

Active member
Not sure if you are meaning to add a study alert or something else. This particular study does not show up to be selectable when trying to setup a study alert. I also would like to be able SCAN for this condition which will require a custom scan script I am afraid.
Nah, what he's saying is set is your TS and see where the dots plot. Then just set an individual stock alert on the price that the TS sets. Works just fine
 
Last edited:

bigpemby

New member
A static price alert won't work because the ATR trailing stop is dynamically changing with each bar. Maybe I am confused. See image link attached. I want to be alerted when the dots change to pink or change to blue. Then be able to scan for a daily/hourly condition change to find symbols that have recently changed.

 

wtf_dude

Active member
A static price alert won't work because the ATR trailing stop is dynamically changing with each bar. Maybe I am confused. See image link attached. I want to be alerted when the dots change to pink or change to blue. Then be able to scan for a daily/hourly condition change to find symbols that have recently changed.

Oh duh, sorry man I forgot the fact that I change the ATR settings to a much wider (50 day) period to eliminate chops personally. I'll have to let somebody else take this one on. I'm sure it can be done just by just ripping and modifying the code from the ATR TS study itself.
 

wtf_dude

Active member
A static price alert won't work because the ATR trailing stop is dynamically changing with each bar. Maybe I am confused. See image link attached. I want to be alerted when the dots change to pink or change to blue. Then be able to scan for a daily/hourly condition change to find symbols that have recently changed.
Hey, I finally sat down and looked this. This will at least add alerts to the study itself when it flips from buy to sell on the stop. As far as a scan or adding the percentage, you'll have to code that in yourself.

Code:
# TD Ameritrade IP Company, Inc. (c) 2009-2020
# alert mod by WTF_Dude
#

input trailType = {default modified, unmodified};
input ATRPeriod = 5;
input ATRFactor = 3.5;
input firstTrade = {default long, short};
input averageType = AverageType.WILDERS;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

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

def BuySignal = Crosses(state == state.long, 0, CrossingDirection.ABOVE);
def SellSignal = Crosses(state == state.short, 0, CrossingDirection.ABOVE);

plot TrailingStop = trail;

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





# Alerts:

input alerttext="ATR stop switch";
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
Alert(BuySignal, alerttext, AlertType, AlertSound);
Alert(SellSignal,alerttext, AlertType, AlertSound);
 
Last edited:

bigpemby

New member
This is fantastic! Thank you very much. Wish I could code. I have another post I made yesterday about an exit order I am trying to create. It sure seems simple enough but I just cannot get the mechanics to work out.
 

modernmind

New member
This is fantastic! Thank you very much. Wish I could code. I have another post I made yesterday about an exit order I am trying to create. It sure seems simple enough but I just cannot get the mechanics to work out.
Did you ever find a solution to your scan request for the change in ATR direction? I'm interested in this scan as well.
 

ShadowJack

New member
I am using the following custom filter to scan for stocks that change direction today

Code:
input trailType = {default modified, unmodified};
input periods = 21;
input multiplier = 3.0;
input firstTrade = {default long, short};
input averageType = AverageType.WILDERS;
input indicator = {both, default long, short};

def yesterdayATR = ATRTrailingStop("trail type" = trailType, "atr period" = periods, "atr factor" = multiplier, "first trade" = firstTrade, "average type" = averageType) from 1 bar ago;
def yesterdayPrice = close from 1 bar ago;
def todayATR = ATRTrailingStop("trail type" = trailType, "atr period" = periods, "atr factor" = multiplier, "first trade" = firstTrade, "average type" = averageType);
def todayPrice = close;

def buyIndicator = (indicator == indicator.both or indicator == indicator.long) and (todayATR <= todayPrice and yesterdayATR >= yesterdayPrice);
def sellIndicator = (indicator == indicator.both or indicator == indicator.short) and (todayATR >= todayPrice and yesterdayATR <= yesterdayPrice);

plot keep = if buyIndicator or sellIndicator then todayATR else Double.NaN;
 
Hey guys, I'm baffled that I cannot get this simple ATR trailing stop attempt working correctly. I just want to setup a basic ATR trailing stop that stays on the intended side of a trade (as opposed to the built-in indicator that flips sides depending on price action). For some reason, though, if you plot the following code the plot does not obey the Max or Min functions and will decrease (if max used) or increase (if min used) with price action. Anyone know what I'm doing wrong?

Code:
input ATRPeriod = 5;
input ATRFactor = 3.5;

def loss = ATRFactor * atr(atrperiod);
def traillong = close - loss;
def trailshort = close + loss;

plot atrtraillong = Max(traillong[1], traillong);
plot atrtrailshort = Min(trailshort[1], trailshort);
 

mashume

Well-known member
VIP
Lifetime
Hey guys, I'm baffled that I cannot get this simple ATR trailing stop attempt working correctly. I just want to setup a basic ATR trailing stop that stays on the intended side of a trade (as opposed to the built-in indicator that flips sides depending on price action). For some reason, though, if you plot the following code the plot does not obey the Max or Min functions and will decrease (if max used) or increase (if min used) with price action. Anyone know what I'm doing wrong?

Code:
input ATRPeriod = 5;
input ATRFactor = 3.5;

def loss = ATRFactor * atr(atrperiod);
def traillong = close - loss;
def trailshort = close + loss;

plot atrtraillong = Max(traillong[1], traillong);
plot atrtrailshort = Min(trailshort[1], trailshort);

Does this do something like what you want?

Code:
input ATRPeriod = 5;
input ATRFactor = 3.5;

def loss = ATRFactor * atr(atrperiod);
def traillong = close - loss;
def trailshort = close + loss;
addLabel(YES, text = trailshort, color.dark_green);
addLabel(YES, text = traillong, color.dark_red);
def bar = barnumber();


def atrtraillong = if bar >= ATRPeriod then max(atrtraillong[1], traillong) else traillong;
def atrtrailshort =  if bar >= ATRPeriod then min(atrtrailshort[1], trailshort) else trailshort;


plot atr_long = atrtraillong;
plot atr_short = atrtrailshort;

-mashume
 
@mashume Unfortunately not.. that just looks to plot horizontal lines very far from the price action.

The behavior I'm looking for is to plot a line that trails the highest close price - ATR * multiplier, and a second plot that trails the lowest close + ATR * multiplier, just like the built-in ATR Trailing Stop indicator does. However, the built-in indicator swaps sides of the price when price closes above/below the trailing stop. I just want 2 lines that stay on their side: one above the price, one below.

I still can't figure out why my code isn't working, and I greatly appreciate any help you or anyone can give!
 

XeoNoX

Well-known member
VIP
Not sure what you are trying to do, but here you go with labels to show you that the values are correct. The Highest 4 day price minus the ATR multiplied by 1.


Code:
#####

declare upper;

def ATRLength = 4;
input averagetype = AverageType.SIMPLE;
def BasePeriod = AggregationPeriod.FOUR_DAYS;
input showlabel = yes;
input showBubble = yes;
input ShiftBubble = 5;
Input Multiplied_by = 1;
def n1 = ShiftBubble + 1;


def ATR1 = MovingAverage (averagetype, TrueRange(high(period = BasePeriod)[1], close(period = BasePeriod)[1], low(period = BasePeriod)[1]), ATRLength);

def Todays_High = Highest(high(period = BasePeriod)[0], 1);
def Todays_Low = Lowest(low(period = BasePeriod)[0], 1);


plot Todays_High_Multiplied = (todays_High - atr1) *(Multiplied_by) ;
plot Todays_Low_Multiplied = (todays_Low -atr1) * (Multiplied_by);

Todays_High_Multiplied.SetDefaultColor(Color.GRAY);
Todays_Low_Multiplied.SetDefaultColor(Color.GRAY);
Todays_High_Multiplied.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
Todays_Low_Multiplied.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

def cond = showBubble and IsNaN(close[ShiftBubble]) and !IsNaN(close[n1]) ;
AddChartBubble(cond, Todays_High_Multiplied, Concat("Todays High: ", Round(Todays_High_Multiplied)), Color.MAGENTA);
AddChartBubble(cond, Todays_Low_Multiplied, Concat("Todays Low: ", Round(Todays_Low_Multiplied)), Color.MAGENTA);
AddLabel(showlabel, "4 Day ATR High: " + Round(todays_High , 2)  + " (" + atrlength + "D.Avg): ",color.DARK_ORANGE);
AddLabel(showlabel, "4 Day ATR Low: " + Round(todays_Low , 2)  + " (" + atrlength + "D.Avg): ",color.DARK_ORANGE);
AddLabel(showlabel, "ATR Range: " + Round(ATR1 , 2)  + " (" + atrlength + "D.Avg): ",color.DARK_ORANGE);
 
I really appreciate the help - you gave me exactly what I asked for. I realize now that I'm a dummy and what I really wanted to accomplish is not possible without implimenting logic to say if I'm in a trade or not, since the plots have to disappear otherwise if I'm flat.

What I am trying to accomplish is just to have a trailing stop when I enter into orders, so that I can effectively capture profits. I want the magnitude of that trailing stop to = ATR * multiplier.

Actually, after looking at it again, @mashume made just what I need, except I need the plot to start over again each time an order is entered. I'm not even sure this is possible to use when backtesting, like I'd like, since I'm not sure if you can get it to recognize any of the Portfolio functions in this context (I haven't been able to while using the below change to @mashume's code)

Code:
def atrtraillong = if isnan(entryprice()) then double.NaN else if bar >= ATRPeriod then max(atrtraillong[1], traillong) else traillong;
def atrtrailshort =  if isnan(entryprice()) then double.NaN else if  bar >= ATRPeriod then min(atrtrailshort[1], trailshort) else trailshort;

I've no doubt you guys are far more clever than me and can figure out a way, though!
 

mashume

Well-known member
VIP
Lifetime
@TraderKevin I wrote some code somewhere around here that looked at whether you were in a trade for trying to plot ToS mobile style lines. You look at
Code:
if isnan(entryprice[1]) and !isnan(entryprice) then IN_TRADE else NOT_IN_TRADE
but that's pseudo-code not real code to put in your script.

-mashume
 

TechGuy

New member
@wtf_dude Hi, I am new to Thinkscript and I appreciate your help. I am trying to program a scan using your example above for a price going either up or down though an ATR trailing stop. I have my scan on an ATR period of 5 and a Factor of 3.5. I have the scan timeframe set currently at a 3 minute interval. However, the scan does not accurately show new longs and shorts. What am I missing? Thanks.
 

wtf_dude

Active member
Hi, I am new to Thinkscript and I appreciate your help. I am trying to program a scan using your example above for a price going either up or down though an ATR trailing stop. I have my scan on an ATR period of 5 and a Factor of 3.5. I have the scan timeframe set currently at a 3 minute interval. However, the scan does not accurately show new longs and shorts. What am I missing? Thanks.
hmm probably just need to correct your condition wizard. So on the pop up menu select:

First column select price, close
middle column select "crosses above" (to get a blue dot/bull)
last column select study, ATRtrailingstop and leave the default settings
 

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
175 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.
Top