ATR Trailing Stop Strategy by ceyhun For ThinkOrSwim

2Snapzzz

New member
Hi everyone,

I am still pretty new to this. I tried searching the forums and wasn't able to find anything similar to this script from TradingView. I am trying to mimic an ATR Trail Stop Strategy script that was created by Ceyhun. Any help is greatly appreciated. Here is the link to his script. https://www.tradingview.com/script/cj3MJWNz/
a1.png


Ruby:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ceyhun

//@version=4
strategy("ATR Trailing Stop Strategy by ceyhun", overlay=true)

/////////notes////////////////////////////////////////
// This is based on the ATR trailing stop indicator //
// width addition of two levels of stops and //
// different interpretation. //
// This is a fast-reacting system and is better //
// suited for higher volatility markets //
//////////////////////////////////////////////////////

SC = input(close, "Source", input.source)

// Fast Trail //
AP1 = input(5, "Fast ATR period", input.integer) // ATR Period
AF1 = input(0.5, "Fast ATR multiplier", input.float) // ATR Factor
SL1 = AF1 * atr(AP1) // Stop Loss
Trail1 = 0.0
Trail1 := iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1), iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0), min(nz(Trail1[1], 0), SC + SL1), iff(SC > nz(Trail1[1], 0), SC - SL1, SC + SL1)))

// Slow Trail //
AP2 = input(10, "Slow ATR perod", input.integer) // ATR Period
AF2 = input(3, "Slow ATR multiplier", input.float) // ATR Factor
SL2 = AF2 * atr(AP2) // Stop Loss
Trail2 = 0.0
Trail2 := iff(SC > nz(Trail2[1], 0) and SC[1] > nz(Trail2[1], 0), max(nz(Trail2[1], 0), SC - SL2), iff(SC < nz(Trail2[1], 0) and SC[1] < nz(Trail2[1], 0), min(nz(Trail2[1], 0), SC + SL2), iff(SC > nz(Trail2[1], 0), SC - SL2, SC + SL2)))

// Bar color for trade signal //
Green = Trail1 > Trail2 and close > Trail2 and low > Trail2
Blue = Trail1 > Trail2 and close > Trail2 and low < Trail2
Red = Trail2 > Trail1 and close < Trail2 and high < Trail2
Yellow = Trail2 > Trail1 and close < Trail2 and high > Trail2

// Signals //
Bull = barssince(Green) < barssince(Red)
Bear = barssince(Red) < barssince(Green)

Buy = crossover(Trail1, Trail2)
Sell = crossunder(Trail1, Trail2)

TS1 = plot(Trail1, "Fast Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.blue : color.yellow, linewidth=2, display=display.none)
TS2 = plot(Trail2, "Slow Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.green : color.red, linewidth=2)
fill(TS1, TS2, Bull ? color.new(color.green,90) : color.new(color.red,90))

plotcolor = input(true, "Paint color on chart", input.bool)

bcl = iff(plotcolor == 1, Blue ? color.blue : Green ? color.lime : Yellow ? color.yellow : Red ? color.red : color.white, na)
barcolor(bcl)

if Buy
strategy.entry("Buy", strategy.long, comment="Buy")

if Sell
strategy.entry("Sell", strategy.short, comment="Sell")
 
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

here is my attempt at converting that TV pinescript code to TOS.
you can turn the fast and slow lines on and off. both need to be on for the cloud shading to be drawn, between them.

lookback = 66
i used GetMaxValueOffset() that uses a lookback number, that is how many bars it looks back to find a signal. i guessed and came up with 66. it may need to be adjusted, i'm not sure. this seems to work, so i didn't create a fold loop.

i added strategy code lines (addorder) at the end, but left them commented out.
this could be loaded as a strategy, change the name, then enable the code lines and set either or both inputs to yes.(enable longs , enable shorts)

i've never made a pine script, so this might be off a little? i just looked up a couple of functions here.
https://www.tradingview.com/pine-script-reference/
i left the original code in and commented it out, so others could verify it and learn from it.

Ruby:
# trailstop_tv_01

# ----------------------------
# https://www.tradingview.com/script/cj3MJWNz/
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © ceyhun

#//@version=4
#strategy("ATR Trailing Stop Strategy by ceyhun", overlay=true)

#/////////notes////////////////////////////////////////
#// This is based on the ATR trailing stop indicator //
#// width addition of two levels of stops and //
#// different interpretation. //
#// This is a fast-reacting system and is better //
#// suited for higher volatility markets //
#//////////////////////////////////////////////////////

def bn = BarNumber();
def na = Double.NaN;

#SC = input(close, "Source", input.source)
def sc = close;

# The type of moving average to be used in calculations: simple, exponential, weighted, Wilder's, or Hull.
#input avgtype = averagetype.exponential;
input atr_averageType = AverageType.WILDERS;


#// Fast Trail //
#AP1 = input(5, "Fast ATR period", input.integer) // ATR Period
#AF1 = input(0.5, "Fast ATR multiplier", input.float) // ATR Factor
#SL1 = AF1 * atr(AP1) // Stop Loss
input show_fast_trail = yes;

input ap1_fast_ATR_period = 5;
input af1_fast_ATR_multiplier = 0.5;
def ATRfast = MovingAverage(atr_averageType, TrueRange(high, close, low), ap1_fast_ATR_period);
def sl1 = af1_fast_ATR_multiplier * ATRfast;



# nz( )
# Replaces NaN values with zeros (or given value) in a series.
# nz(x, y) -- integer
#  RETURNS
#   Two args version: returns x if it's a valid (not NaN) number, otherwise y
#   One arg version: returns x if it's a valid (not NaN) number, otherwise 0
#
# tos ver
#   if isnan(x) then y else x


# ---------------------------
#Trail1 = 0.0
#Trail1 := iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1), iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0), min(nz(Trail1[1], 0), SC + SL1), iff(SC > nz(Trail1[1], 0), SC - SL1, SC + SL1)))
# ----------------------
#  restructure prev line
# if(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0),
#   max(nz(Trail1[1], 0), SC - SL1),
# iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0),
#   min(nz(Trail1[1], 0), SC + SL1),
# iff(SC > nz(Trail1[1], 0),
#   SC - SL1, SC + SL1)))
# -------------------------


#  nz(Trail1[1], 0)  =  (if isnan(trail1[1]) then 0 else trail1[1])

def trail1 = if bn == 1 then 0
else if  (SC > (if isnan(trail1[1]) then 0 else trail1[1])) and (SC[1] > (if isnan(trail1[1]) then 0 else trail1[1])) then
  max( (if isnan(trail1[1]) then 0 else trail1[1]), (SC - SL1))
else if(SC < (if isnan(trail1[1]) then 0 else trail1[1])) and (SC[1] < (if isnan(trail1[1]) then 0 else trail1[1])) then
  min( (if isnan(trail1[1]) then 0 else trail1[1]) , SC + SL1)
else if(SC > (if isnan(trail1[1]) then 0 else trail1[1])) then ( SC - SL1) else (SC + SL1) ;


#// Slow Trail //
#AP2 = input(10, "Slow ATR perod", input.integer) // ATR Period
#AF2 = input(3, "Slow ATR multiplier", input.float) // ATR Factor
#SL2 = AF2 * atr(AP2) // Stop Loss
input show_slow_trail = yes;

input ap2_slow_ATR_period = 10;
input af2_slow_ATR_multiplier = 3.0;
def ATRslow = MovingAverage(atr_averageType, TrueRange(high, close, low), ap2_slow_ATR_period);
def sl2 = af2_slow_ATR_multiplier * ATRslow;



#Trail2 = 0.0
#Trail2 := iff(SC > nz(Trail2[1], 0) and SC[1] > nz(Trail2[1], 0), max(nz(Trail2[1], 0), SC - SL2), iff(SC < nz(Trail2[1], 0) and SC[1] < nz(Trail2[1], 0), min(nz(Trail2[1], 0), SC + SL2), iff(SC > nz(Trail2[1], 0), SC - SL2, SC + SL2)))

def trail2 = if bn == 1 then 0
else if  (SC > (if isnan(trail2[1]) then 0 else trail2[1])) and (SC[1] > (if isnan(trail2[1]) then 0 else trail2[1])) then
  max( (if isnan(trail2[1]) then 0 else trail2[1]), (SC - SL2))
else if(SC < (if isnan(trail2[1]) then 0 else trail2[1])) and (SC[1] < (if isnan(trail2[1]) then 0 else trail2[1])) then
  min( (if isnan(trail2[1]) then 0 else trail2[1]) , SC + SL2)
else if(SC > (if isnan(trail2[1]) then 0 else trail2[1])) then ( SC - SL2) else (SC + SL2) ;



#// Bar color for trade signal //
#Green = Trail1 > Trail2 and close > Trail2 and low > Trail2
#Blue = Trail1 > Trail2 and close > Trail2 and low < Trail2
#Red = Trail2 > Trail1 and close < Trail2 and high < Trail2
#Yellow = Trail2 > Trail1 and close < Trail2 and high > Trail2

def Green = (Trail1 > Trail2) and (close > Trail2) and (low > Trail2);
def Blue = (Trail1 > Trail2) and (close > Trail2) and (low < Trail2);
def Red = (Trail2 > Trail1) and (close < Trail2) and (high < Trail2);
def Yellow = (Trail2 > Trail1) and (close < Trail2) and (high > Trail2);

input show_cloud_between_trails = yes;

#// Signals //
#Bull = barssince(Green) < barssince(Red)
#Bear = barssince(Red) < barssince(Green)

# returns the offset of the highest value of data for the last length bars.
# guess at a length to look back for a green or red
input lookback = 66;
# test code
#def test1 = GetMaxValueOffset(green, lookback);
#addchartbubble(1, low, bn + "\n" + green + "\n" + test1, (if green then color.green else color.gray), no);

def Bull = GetMaxValueOffset(green, lookback) < GetMaxValueOffset(red, lookback);
def Bear = GetMaxValueOffset(red, lookback) < GetMaxValueOffset(green, lookback);


#Buy = crossover(Trail1, Trail2)
#Sell = crossunder(Trail1, Trail2)
def Buy = Trail1 crosses above Trail2;
def Sell = Trail1 crosses below Trail2;


#TS1 = plot(Trail1, "Fast Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.blue : color.yellow, linewidth=2, display=display.none)
#TS2 = plot(Trail2, "Slow Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.green : color.red, linewidth=2)

#input show_fast_trail = yes;
plot ts1 = if show_fast_trail then trail1 else na;
ts1.DefineColor("ftrail1up", color.blue);
ts1.DefineColor("ftrail1dwn", color.yellow);
ts1.AssignValueColor(if (Trail1 > Trail2 ) then ts1.color("ftrail1up") else ts1.color("ftrail1dwn"));
# x.SetDefaultColor(Color.red);
# x.setlineweight(1);
# x.hidebubble();

#input show_slow_trail = yes;
plot ts2 = if show_slow_trail then trail2 else na;
ts2.DefineColor("strail1up", color.green);
ts2.DefineColor("strail1dwn", color.red);
ts2.AssignValueColor(if (Trail1 > Trail2 ) then ts2.color("strail1up") else ts2.color("strail1dwn"));
# x.SetDefaultColor(Color.red);
# x.setlineweight(1);
# x.hidebubble();


#fill(TS1, TS2, Bull ? color.new(color.green,90) : color.new(color.red,90))

# draw shading between 2 lines
def top1 = if show_cloud_between_trails then ts1 else na;
addcloud(top1, ts2, color.green, color.red);



#plotcolor = input(true, "Paint color on chart", input.bool)
#bcl = iff(plotcolor == 1, Blue ? color.blue : Green ? color.lime : Yellow ? color.yellow : Red ? color.red : color.white, na)
#barcolor(bcl)
#if Buy
#strategy.entry("Buy", strategy.long, comment="Buy")
#if Sell
#strategy.entry("Sell", strategy.short, comment="Sell")


# --------------------------------

# strategy code

# longs
input enable_strategy_longs = no;
#AddOrder(OrderType.BUY_to_open, (enable_strategy_longs and buy), tickcolor = Color.green, arrowcolor = Color.green, name = "BUY open" );
#AddOrder(OrderType.SELL_to_close, (enable_strategy_longs and sell), tickcolor = color.red, arrowcolor = color.red, name = "BUY close" );


# shorts
input enable_strategy_shorts = no;
#AddOrder(OrderType.sell_to_open, (enable_strategy_shorts and sell), tickcolor = Color.green, arrowcolor = Color.green, name = "BUY open" );
#AddOrder(OrderType.buy_to_close, (enable_strategy_shorts and buy), tickcolor = color.red, arrowcolor = color.red, name = "BUY close" );



# ---------------------------

#ATR
#input length = 14;
#input averageType = AverageType.WILDERS;
#plot ATR = MovingAverage(averageType, TrueRange(high, close, low), length);
#ATR.SetDefaultColor(GetColor(8));

#

4tlePzm.jpg
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
371 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