Help with automatic stop loss line

Christopher84

Well-known member
VIP
Below is an example of what I am working with. I am new to thinkscript and doing my best to learn quickly. I am hoping to generate a stop loss line when my signal is triggered (similar to what is shown in the reversal indicator), however I do not want it to repaint. Any thoughts or suggestions to get me going in the right direction is very much appreciated.

Code:
#KELTNER

declare weak_volume_dependency;

input displace = 0;
input factor = 2.5;
input length = 20;
input price = open;
input averageType = AverageType.SIMPLE;
input trueRangeAverageType = AverageType.SIMPLE;

def shift = factor * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), length);

def average = MovingAverage(averageType, price, length);

plot Avg = average[-displace];
Avg.SetDefaultColor(GetColor(1));

plot Upper_BandK1 = average[-displace] + shift[-displace];
Upper_BandK1.SetDefaultColor(GetColor(8));

plot Lower_BandK1 = average[-displace] - shift[-displace];
Lower_BandK1.SetDefaultColor(GetColor(5));


#def price1 = open [-1];


plot isBelow = price crosses below Upper_BandK1;
plot isAbove = price crosses above Lower_BandK1;
 
Last edited:
@Christopher84 Where would the stop loss lines be positioned...??? I don't recall there being stop loss lines in the other study but that's a moot point as we'll just focus on the code posted here...

I have also edited the bottom of your code to the following so the arrows paint properly...

Ruby:
plot isBelow = price crosses below Upper_BandK1;
isBelow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
isBelow.SetLineWeight(1);
isBelow.SetDefaultColor(Color.RED);

plot isAbove = price crosses above Lower_BandK1;
isAbove.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
isAbove.SetLineWeight(1);
isAbove.SetDefaultColor(Color.GREEN);
 

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

That looks great! As far as the positioning of the stop loss, I was hoping for something similar to what was shown in the reversal indicator but I am open to suggestions. Possibly putting a trailing stop a certain percent below/above (buy/sell) the entry, or using the most recent pivot high or low. Thank you so much for taking the time to look at this. I really do appreciate it.
1614191151149.png
 
Last edited:
@Christopher84 Where you decide on Stop Loss depends on several factors, including your comfort zone for Risk/Reward... Some use the previous Low, others use a fixed percentage or price amount... It all comes down to how much you are willing to lose... I usually go for 1.5:1 to 3:1 Win/Loss Ratio for quick scalps and might set my Stop Loss at 0.10 for a trade I expect to run and then monitor for a manual exit... If it pulls back I might adjust lower but not usually... If it pulls back and I Stop Out there will be another trade and I've cut my losses... If your Stop Loss gets hit a lot then that is an indication that you are picking the wrong entry point to begin with and need to refine your skills at entries...

If you want them to paint on your charts then they are just soft Stop Loss points anyway... I set my Limit and Stop Loss for live trades in Active Trader so they are hard limits... If I want a soft stop or limit I draw them manually based on Support and Resistance... Once you come up with a Stop Loss strategy it could be coded in but you need to have one that you have monitored manually first... Otherwise we're all spinning our wheels coding logic that will just need to be changed...

And just so you know, if you ever want to backtest by changing a Study to a Strategy, I have never seen or coded a stop loss that was as accurate as my own manual ones or the live ones in Active Trader... Trailing Stop Loss code in Strategies are a disaster... I wish I could state otherwise but I just made more failed attempts two weeks ago that further confirms my stance on the matter...
 
@Christopher84 Where you decide on Stop Loss depends on several factors, including your comfort zone for Risk/Reward... Some use the previous Low, others use a fixed percentage or price amount... It all comes down to how much you are willing to lose... I usually go for 1.5:1 to 3:1 Win/Loss Ratio for quick scalps and might set my Stop Loss at 0.10 for a trade I expect to run and then monitor for a manual exit... If it pulls back I might adjust lower but not usually... If it pulls back and I Stop Out there will be another trade and I've cut my losses... If your Stop Loss gets hit a lot then that is an indication that you are picking the wrong entry point to begin with and need to refine your skills at entries...

If you want them to paint on your charts then they are just soft Stop Loss points anyway... I set my Limit and Stop Loss for live trades in Active Trader so they are hard limits... If I want a soft stop or limit I draw them manually based on Support and Resistance... Once you come up with a Stop Loss strategy it could be coded in but you need to have one that you have monitored manually first... Otherwise we're all spinning our wheels coding logic that will just need to be changed...

And just so you know, if you ever want to backtest by changing a Study to a Strategy, I have never seen or coded a stop loss that was as accurate as my own manual ones or the live ones in Active Trader... Trailing Stop Loss code in Strategies are a disaster... I wish I could state otherwise but I just made more failed attempts two weeks ago that further confirms my stance on the matter...
Thank you for your candor. I can see how it could be very difficult to code trailing stops. Your scalping risk/reward comfort zone is similar to the ratio that I use on 10 minute charts for intraday. Using .10 for swing trades on a 1-4 hour time frame seems pretty reasonable. Have you had any luck with coding something that would work for stop loss given .10 for swing trades on the 1-4 hour charts?
 
Hi

I am trying to calculate the difference between the last low of a bar and the last support.

I can plot it on the chart :

plot pivotlow = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

pivotlow.setPaintingStrategy(PaintingStrategy.HORIZONTAL);


but I can't keep the value of my pivot low to calculate my max stop loss:

def pivotlowloss = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

def maxstoploss = close - pivotlossloss;

def maxstoploss1 = if lowerlow1 then maxstoploss else Double.NaN ;

AddLabel(yes, maxstoploss1);

Any idea?
Thank you
 
Hi

I am trying to calculate the difference between the last low of a bar and the last support.

I can plot it on the chart :

plot pivotlow = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

pivotlow.setPaintingStrategy(PaintingStrategy.HORIZONTAL);


but I can't keep the value of my pivot low to calculate my max stop loss:

def pivotlowloss = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

def maxstoploss = close - pivotlossloss;

def maxstoploss1 = if lowerlow1 then maxstoploss else Double.NaN ;

AddLabel(yes, maxstoploss1);

Any idea?
Thank you

to keep the value of a variable, from bar to bar, you need to read the previous value and pass it on the the current variable
this is called recursive

to keep the most recent value of pivotlow , use something like this
if pivotlow is not an error, then save it, if an error then read the previous value
Ruby:
def pivotlowvalue = if !isnan(pivotlow) then pivotlow else pivotlowvalue[1];


recursive info
 
Last edited:
Hi

I am trying to calculate the difference between the last low of a bar and the last support.

I can plot it on the chart :

plot pivotlow = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

pivotlow.setPaintingStrategy(PaintingStrategy.HORIZONTAL);


but I can't keep the value of my pivot low to calculate my max stop loss:

def pivotlowloss = if close [2] < open[2] and close[1] > open[1] then low [1] else Double.NaN ;

def maxstoploss = close - pivotlossloss;

def maxstoploss1 = if lowerlow1 then maxstoploss else Double.NaN ;

AddLabel(yes, maxstoploss1);

Any idea?
Thank you
Hi @wam1234, can you share your final code for stop loss? Thanks!
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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