Having Trouble with Stop Loss Code

Bingy

Member
Hey Guys,

I'm new to the forum, but have been a long time lurker. I'm currently working on a ThinkScript Strategy and I'm trying to backtest it using ThinkorSwim's "On-Demand" feature. The strategy seems promising, but like any good strategy, it's partially dependent on the stop loss strategy to get an accurate feel for how well the strategy is working over a given timeframe.

Essentially, what I'm wanting it to do is to check for the lowest low within the previous 4 bars PRIOR to the "BuySignal" and then I want it to trigger the stop loss if the current bar closes below this low.

I've tried so many different ways and have spent hours trying to figure this out to no avail, so I'm hoping someone here can help me after I've tried helping myself. Thanks in advance!!


#CODE


def BuySignal = SemiCondition and (CAM_UP or CAM_PB or CAM_DN) and BearPower < -20 and EOM < 0 and LowerVolatility;

def ExitSignal = PercentBcross_DWN_Exceltrade;


#############################
#############################
#*********STOP LOSS DEF NEEDS TO BE COMPLETED IN THIS REGION
def Stop_loss = ;


############################
############################



# Define order placement
AddOrder(OrderType.BUY_TO_OPEN, BuySignal, open[-1], 4, tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "Buy");


#Stop loss
AddOrder(OrderType.SELL_TO_CLOSE, Stop_Loss, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Stopped Out");




AddOrder(OrderType.SELL_TO_CLOSE, ExitSignal, open[-1], 4, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Sell");
 
Last edited by a moderator:
Have you tried something like this?

def Stop_loss = if BuySignal then Lowest(low, 4) else Stop_loss[1];
AddOrder(OrderType.SELL_TO_CLOSE, low < Stop_Loss, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Stopped Out");


This will reset the stop loss value to the lowest prior 4 bars each time a BuySignal occurs. It will then bring that value forward until a new BuySignal occurs.

The condition in the AddOrder section will trigger when the low is below the Stop_Loss value.
 
Have you tried something like this?

def Stop_loss = if BuySignal then Lowest(low, 4) else Stop_loss[1];
AddOrder(OrderType.SELL_TO_CLOSE, low < Stop_Loss, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Stopped Out");


This will reset the stop loss value to the lowest prior 4 bars each time a BuySignal occurs. It will then bring that value forward until a new BuySignal occurs.

The condition in the AddOrder section will trigger when the low is below the Stop_Loss value.


Thanks!
 
Hey Guys,

I'm new to the forum, but have been a long time lurker. I'm currently working on a ThinkScript Strategy and I'm trying to backtest it using ThinkorSwim's "On-Demand" feature. The strategy seems promising, but like any good strategy, it's partially dependent on the stop loss strategy to get an accurate feel for how well the strategy is working over a given timeframe.

Essentially, what I'm wanting it to do is to check for the lowest low within the previous 4 bars PRIOR to the "BuySignal" and then I want it to trigger the stop loss if the current bar closes below this low.

I've tried so many different ways and have spent hours trying to figure this out to no avail, so I'm hoping someone here can help me after I've tried helping myself. Thanks in advance!!


#CODE


def BuySignal = SemiCondition and (CAM_UP or CAM_PB or CAM_DN) and BearPower < -20 and EOM < 0 and LowerVolatility;

def ExitSignal = PercentBcross_DWN_Exceltrade;


#############################
#############################
#*********STOP LOSS DEF NEEDS TO BE COMPLETED IN THIS REGION
def Stop_loss = ;


############################
############################



# Define order placement
AddOrder(OrderType.BUY_TO_OPEN, BuySignal, open[-1], 4, tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "Buy");


#Stop loss
AddOrder(OrderType.SELL_TO_CLOSE, Stop_Loss, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Stopped Out");



hal_trail hal_test
AddOrder(OrderType.SELL_TO_CLOSE, ExitSignal, open[-1], 4, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Sell");

you didn't provide any signal code, so i had to create some for testing. this uses 2 averages to create buy and sell signals.

you may find that using a constant value for a stop, allows price to drop and lose all of the profits.

here is a study for experimenting with. can choose,
..your stop method or
..create a trailing stop by recalculating the low on every bar.


Code:
#template_buysell_01c

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

# /////////////////////////////
# test data
# for buying , short avg crossing above long avg

def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 33;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);


input show_lines = yes;
plot z1 = if show_lines then ma1 else na;
 z1.SetDefaultColor(GetColor(1));
 #z1.setlineweight(1);
 z1.HideBubble();
plot z2 = if show_lines then ma2 else na;
 z2.SetDefaultColor(GetColor(2));
 #z2.setlineweight(1);
 z2.HideBubble();

def ma1xup = (ma1 crosses above ma2);
def ma1xdwn = (ma1 crosses below ma2);

# /////////////////////////////
#======================
def buy = ma1xup;
def sell = ma1xdwn;

#======================

def long;
def short;
if bn == 1 then {
    long = 0;
    short = 0;
} else if sell and !sell[1] then {
    long = 0;
    short = 1;
} else if buy and !buy[1] then {
    long = 1;
    short = 0;
} else {
    long = long[1];
    short = short[1];
}

def long_open = !long[1] and long;
def long_close = long[1] and !long;
def short_open = !short[1] and short;
def short_close = short[1] and !short;

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

# stop level
input use_a_trailing_stop = yes;

input stoplen = 4;
def upstop_level = if bn == 1 then 0
 else if long_close[1] then 0
 else if long_open or (use_a_trailing_stop and long) then max(upstop_level[1], lowest(low[1], stoplen))
 else upstop_level[1];

# plot stop line
plot z5 = if upstop_level > 0 then upstop_level else na;
z5.SetDefaultColor(color.yellow);


#----------------
# test data

input buysell_vert_lines = no;
addverticalline(buysell_vert_lines and ma1xup, "buy", color.green);
addverticalline(buysell_vert_lines and ma1xdwn, "sell", color.red);

addchartbubble(0, low,
buy + " B\n" +
long + " L\n" +
sell + " S\n" +
short + " S\n"
, color.yellow, no);

#


flat stop line
SrbN74n.jpg


trailing stop
FKNdI6f.jpg
 
Last edited:

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

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
279 Online
Create Post

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