Posts Tagged ‘trailing_stop’

Tutorial: Trailing Stop Strategies for Think or Swim

May 14, 2009

I have received lots of requests for making a trailing stop strategy work in Think or Swim. Unfortunately, due to the way that ToS currently works with strategies, there is no way to make your entry and exit strategies “talk” to each other automatically. But it is possible to get trailing stop strategies to work! It just takes some extra elbow grease.

In general, any intelligent trailing stop must have knowledge of the entry point, so it knows where to start trailing. You can use “dumb” stops, like my experimental “N bar trailing stop” indicator, that just takes the low / high of N bars back and plots the value. This kind of a number is always on, so to speak. But if you want to trail a certain number of points behind your entry, for example, you can’t use the “dumb” stop method. You have to know where the entry took place. So how do you do it?

The way to make trailing stop strategies work is similar to the way I made my “Volatility-based trailing stop” indicator. The key is to reproduce the entry logic in your stop strategy routine. In that indicator, I had the logic for the long side and the short side together in the same set of code. This is needed for the calculation of the new stop loss value once we switch direction. Along with this, you need to define recursive functions that perform the trailing action. In the Volatility Stop, I’m actually always calculating the values of the long side stops and the short side stops according to the ATR. There is logic to check whether that value is outside the current trailed value (ignore it) or inside the current trailed value (update the trailing stop to the tighter level). This is done for both sides at the same time. There is one more set of logic to decide if we are in the long direction or the short direction, and that tells the indicator which one to plot.

Sound complicated? Actually, it’s HARDER to make the study indicator work than it is to make the strategy work! The strategy will automatically decide if you are long or short based on the criteria you give it for entries and exits. All you have to worry about is reproducing the entry logic in your exit, and the trailing logic.

Time for an example. Say you want to trail a stop N-points below your entry price, and then move it up if “low-N” is greater than the prior trailing stop value.

(Tangent–this is different than a true trailing stop like you might have with your broker, but you have to do it this way if you want to get any backtested results out of the indicator. This is because you will get falsely stopped out if your bar range is greater than your trailing N-points value if you track from the highest high, as a true trailing stop order would. If you could plot this on the tape, tick by tick, then it would work, but for any aggregated candles you have to do it this way. Here’s an explanatory picture:


Confusing, I know; comment if you need more explanation.)

The following strategy skeleton, when fleshed out and paired with an entry strategy, will create a simple “N-points below the low” trailing stop:

declare LONG_EXIT;
# input the number of points to trail under the entry:
input trailstop=2.0;
# Reproduce Your Entry Code Below:

def trigger=if XXXXXX then 1 else 0; # check for entry condition
def orderprice=YYYYYYY; # What price? close, low, high, etc
# Now, initialize Trailing Stop
rec ts=if trigger then orderprice-trailstop else if low-trailstop>ts[1] then low-trailstop else ts[1];
# Send LONG_EXIT order if the low touches the trailing stop (ignore the entry bar):
def stopout=if trigger then 0 else if low<=ts then 1 else 0;

The part about reproducing your entry code should be self explanatory. You put the same code in that you are using for your entry. The strategy skeleton above uses two other lines:

def trigger=if XXXXXX then 1 else 0; # check for entry condition
def orderprice=YYYYYYY; # What price? close, low, high, etc

“Tigger” is the final check for your entry condition. “Orderprice” is where you put the price that you want the trade to be taken at, or the price where you would submit the order.

Now, the part with the recursive trailing logic is trickier, and is done in two parts, like this:

# Now, initialize Trailing Stop
rec ts=if trigger then orderprice-trailstop else if low-trailstop>ts[1] then low-trailstop else ts[1];

In english: If this is the entry bar then set the trailing stop N points below the order price. If it’s not the entry bar, then check if the value of low-N points > the last trailing stop value, and if it is, then that’s the new trailing stop value, but if it’s not, then keep the old one.

Then, you check if you actually get stopped out:

# Send LONG_EXIT order if the low touches the trailing stop (ignore the entry bar):
def stopout=if trigger then 0 else if low<=ts then 1 else 0;

In english: If this is the entry bar, then do nothing. If it’s not the entry bar, then if the low of the bar hit the trailing stop (or went below) then stop out, but if not, then do nothing.

The final step is in the code that actually adds the order:


In english: Add the order if we got a stop out. Use the value of the trailing stop as the order execution price.

This acts like we had an actual stop loss order in the market, and if it was hit we’d get out of the trade. So to wrap it all up, here’s an example set of files I made using a simple EMA Crossover as the entry condition. There are two studies for visualization, and two strategies–one for the entry and one for the exit:

Download Example Files

If you add all of this to a chart, it looks something like this:


Trailing Stop Strategy in Think or Swim. Q.E.D.

You could reverse all of this logic to get the short side strategies as well. Now you should know enough to make your own trailing stop strategies. Unfortunately, I can’t create a standalone trailing stop strategy that you can just drop on a chart. There has to be some editing and coding done each time that you want to use a trailing stop with different strategy of your own. Feel free to ask questions if you need a pointer or two while making your own, I’m glad to help out!

Alternatively, if you would like me to do the work for you and create a custom trailing stop strategy to go along with an entry strategy you already have, contact me and I’ll code it for you for a flat $20 donation. You can choose any trailing style you like–trail N-points, ATR/volatility-based, percentage-based, etc. I do have to ask for new donations even from past donors for this specific offering due to the additional time I have to put in for each request, rather than just giving access to the products of my brain, as it were. The $20 pricing is good if you already have the entry strategy file to send me. If you need the entry strategy developed too, then it becomes a custom development request, and I’ll have to give you a quote on the number of hours it will take in order to determine the pricing. Either way, if you need some work done, send me an email.

Some Updates

February 23, 2009

I made some updates to VWAPALOOZA and to the Volatility-Based Trailing Stop. Check them out if you’re interested.

Volatility-Based Trailing Stop for Think or Swim

January 30, 2009

UPDATE 18 May 2009: Fixed error as noted in comments below (Thanks, Jeff!)

UPDATE 23 Feb 2009: Added option to use High/Low as well as Close as the volatility stop switching trigger. Also changed “AverageTrueRange” to exponential average of High-Low so it works on tick charts.


This Thinkscript indicator is a volatility-based trailing stop, similar to the Chandelier Stop. When direction switches from short to long (or vice versa), the initial stop level is a specified number of multiples of the Average True Range (ATR) of the last ‘n’ bars. Then the value is trailed, getting tighter should volatility decrease or price move to new extremes. A close through the stop level signifies a trend change in this indicator; crossing the value and closing back on the other side does not.

The part of this indicator that was tricky is the trailing stop logic, as well as switching the direction of the indicator–long or short. Thinkscript runs in very linear fashion, and you can’t define an indicator at one point and then change the value at another point. The workaround is to put complicated logic gates into the definition itself.

There are two inputs here: The ATR factor, and the length for the ATR calculation. These can be reset from the studies window without changing the Thinkscript. If you want a different default value, change the code below to the value you want.

The code can be found on my Google site.