• The price of VIP membership is increasing to $199 beginning June 1. Click here to lock in the current rate of $149.

Multi-TimeFrame ATR Trailing Stops for ThinkorSwim

TOS007

New member
This is my first post, a question, really. I have seen plethora of codes for MTF studies on the internet, but having troubles to find any MTF ATR Trailing Stops for thinkscript. I think it is helpful to trade against different time frames. I am asking, if any one of you can kindly write a code for it? Thanks!

Can anyone help me with this code, please? The problem is with the line for plotting the ATR. I truly appreciate for your help. Thanks.

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2009-2020
# MTF_ATR

input Period = aggregationPeriod.DAY;
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(AvgType, close(period = Period), Length);

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"));
 
Last edited by a moderator:

BenTen

Administrative
Staff
VIP
@TOS007 Here is the MTF version of the ATR Trailing Stop indicator

Code:
# ATR Trailing Stop MTF (Multi Timeframe) Version
# Added support for MTF by BenTen at UseThinkScript.com
# Uses the original ATRTrailingStop code provided by ThinkorSwim

input aggregationPeriod = AggregationPeriod.HOUR;
def high = high(period = aggregationPeriod);
def low = low(period = aggregationPeriod);
def close = close(period = aggregationPeriod);

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"));

plot pUp = BuySignal;
pUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
pUp.SetLineWeight(1);
pUp.AssignValueColor(COLOR.CYAN);

plot pDown = SellSignal;
pDown.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
pDown.SetLineWeight(1);
pDown.AssignValueColor(COLOR.MAGENTA);
 

TOS007

New member
Thank you so much!

Let's see how price will behave around Daily ATR. (Hull 34 period)

2MsqIE0.png
 

DanO2020

New member
Great posts above. Is there a way to split the trailing stop for the long only and short only trades? When I use the scripts above sometimes the trails don't work.
 

DanO2020

New member
@BenTen

I've created a strategy to short the MES when MACD value goes below average and when DMI Oscillator is negative. I also have a long in the opposite direction.

Here is the study:

Code:
# Buy= pos MACD, positive DMI+ and positive trailing order

# Sell is DMI- below DMI + or trailing stop loss


# TSL

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

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 ATRMod = ExpAverage(Max(HiLo, Max(HRef, LRef)), 2 * ATRPeriod - 1);
def loss;
switch (trailType) {
case modified:
    loss = ATRFactor * ATRMod;
case unmodified:
    loss = ATRFactor * Average(TrueRange(high,  close,  low),  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"));

plot cross = close crosses TrailingStop;
cross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);




#


# MACD crossover buy on crossover
#

input fastLength = 13;
input slowLength = 21;
input MACDLength = 8;
input averageType = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;

def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);

def Diff = Value - Avg;
def ZeroLine = 0;

def UpSignal = if Diff crosses above ZeroLine then ZeroLine else Double.NaN;
def DownSignal = if Diff crosses below ZeroLine then ZeroLine else Double.NaN;

def Condition1 =
Value[1] < Avg[1] and
Value > Avg;

def Condition4 =

Value[1] > Avg[1] and Value < Avg;


# DMI oscilator
input DMIlength = 10;
input paintBars = yes;
input DMIIaverageType = AverageType.WILDERS;

def diPlus = DMI(DMIlength, averageType)."DI+";
def diMinus = DMI(DMIlength, averageType)."DI-";

def Osc = diPlus - diMinus;
def Hist = Osc;
def DMIZeroLine = 0;




# DMI oscilator




def condition10 = if Osc  > 0 then 1 else 0;

def condition2 = close () > TrailingStop;



def buy = condition10 > 0 and Condition1 > 0 and condition2 > 0;

def sell2 = SellSignal > 0;

def condition5 = if Osc <0 then 1 else 0;

def buy2 = Condition4 > 0 and condition5 > 0;


AddOrder(OrderType.BUY_TO_OPEN, buy, name = "MACD-DI Buy", tickcolor = Color.CYAN, arrowcolor = Color.CYAN);

AddOrder(OrderType.SELL_TO_OPEN, buy2, name = "MACD-DI Short", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);


AddOrder(OrderType.SELL_TO_CLOSE, sell2, name = "SL EXIT", tickcolor = Color.WHITE, arrowcolor = Color.WHITE);

AddOrder(OrderType.BUY_TO_CLOSE, sell2, name = "SL EXIT", tickcolor = Color.RED, arrowcolor = Color.RED);

Here is the screen:

8Y6mxFs.png
 
Last edited by a moderator:

mav12

New member
Hello group,

I'm relatively new to coding TOS.. Tried to paste the code by BenTen into the script editor and it doesn't work. Could anyone suggest how to?
Also, I tried to code a strategy into TOS using different indicators on 2 time frames. TOS staff say it is not possible:

"It's possible you could create a custom study that would only be considered true based on multiple studies if you have some good coding knowledge but we don't offer thinkscript support through chat unfortunately."

Anyone could help please....taking 2 diff indict on 2 time frames?
 

mav12

New member
I went to edit studies, create a new study and added the code into the editor. The study does not show up in a chart. Here is a link to a Google drive with the screenshots.

A6sKxeX.jpg
 
Last edited:

Similar threads

Top