Adding a stoploss line that follows price to existing ThinkScript

azakusa

New member
Looking to add an additional plot line to the thinkscript below.

The desired plot line would follow the current price -4%. Effectively making two lines. One with the current price, and one at 4% below it.

The idea is to use it as a quick visual reference for where my stoploss would reside to help me speed up the decision process on my entries.

I was poking around on the site the closest thing (visually) I came up with was this.
https://usethinkscript.com/threads/bid-ask-spread-lines-indicator-for-thinkorswim.1140/post-8476

Any thoughts anyone?

Code:
#Plots a Horizontal Line that follows the price value selected
input price=close;
input offset=0;
input length = 300;

def sma = SimpleMovingAvg(price, 1, length);
rec line = if IsNaN(sma) then line[1] else sma[offset];
plot priceline=if isnan(sma) then line else double.nan;
priceline.setpaintingStrategy(paintingStrategy.LINE);
priceline.setlineWeight(3);
priceline.setdefaultColor(color.green);
priceline.hideBubble();
 
Solution
The sma method is clean 'cause it only looks at the recent bar.
HighestAll is not recommended by ThinkOrSwim (infer that LowestAll wouldn't be recommended, either):

Per
https://tlc.thinkorswim.com/center/...dvanced/Chapter-12---Past-Offset-and-Prefetch

We strongly recommend that you use the “IsNaN + future offset” method for detection of the last bar, not the popular HighestAll method
...
may result in productivity problems. Besides, the re-calculation mode will be set to once per bar instead of once per quote, which may also affect the output in an unwanted way. Should you need to fix the last bar in your script, use the future offset version

The code...

Pensar

Well-known member
VIP
Looking to add an additional plot line to the thinkscript below.

The desired plot line would follow the current price -4%. Effectively making two lines. One with the current price, and one at 4% below it.

The idea is to use it as a quick visual reference for where my stoploss would reside to help me speed up the decision process on my entries.

I was poking around on the site the closest thing (visually) I came up with was this.
https://usethinkscript.com/threads/bid-ask-spread-lines-indicator-for-thinkorswim.1140/post-8476

Any thoughts anyone?

---------------------
#Plots a Horizontal Line that follows the price value selected
input price=close;
input offset=0;
input length = 300;

def sma = SimpleMovingAvg(price, 1, length);
rec line = if IsNaN(sma) then line[1] else sma[offset];
plot priceline=if isnan(sma) then line else double.nan;
priceline.setpaintingStrategy(paintingStrategy.LINE);
priceline.setlineWeight(3);
priceline.setdefaultColor(color.green);
priceline.hideBubble();
------------------------
@azakusa Something like this?

Code:
input percentoffset = 4;
plot current_price = HighestAll(if IsNaN(close[-1]) then close else Double.NaN);
     current_price.setdefaultcolor(color.cyan);
plot offset_line = LowestAll(current_price - (percentoffset /100*close));
     offset_line.setdefaultcolor(color.red);
 
Last edited:

azakusa

New member
@Pensar
Hello and many thanks for the follow-up.

I have tried out this piece of code, and it seems to plot the price from the previous candles close. But doesnt plot price in realtime like the original code I posted. Also for some reason its drawing the stoploss line at around -3% as opposed to -4%. (?)

It would be quite amazing to see both lines follow realtime price. I'm using this with microcaps on 1 minute charts. So perhaps thats the issue?

Truly appreciate your help. If you have any further thoughts on this I am all ears.

Thanks again.
 

Pensar

Well-known member
VIP
@azakusa So with the math portion of the code I posted, the 4 / 100 = 0.04, or 4% in decimal form. then multiplying that 0.04 by the close ( aka the most current price) should return 4% of the current price's value, which is then subtracted from the priceline to find 4% below it. The code should be correct. That being said, I did just now plot it on a 1 minute microcap chart and noticed that the line is in the area of 3.85% - 4% below the current price. The only thing that I can think of why that is happening is that the calculations as performed by Thinkorswim are not 100% precise.

As for the line plotting at the previous candle's close, perhaps you could share a screenshot of the issue? I've used that version of priceline for some time, and havent had that ever happen on my charts. Given that you are using it on a microcap, perhaps low volume might be causing an issue as well.
 

azakusa

New member
Hello @Pensar

I restarted TOS and the price plot as well as the 4% line are both moving nicely in realtime with the PA now.

Thanks for explaining the code behind the 4% line -this much I get. :) However the percentage difference its plotting is quite off. Seems it doesnt matter what the volumes are. Not sure how you are even getting something close (3.85-4%), what instrument?

If I change the value to 10% its still way off (last screenshot). I will keep tweaking it until it registers something close to 4%.

Even as is, it brilliant, and will be extremely helpful for me. Thank you very much!

See these screenshots below.

amc-trailing4.png


gme-trailing4.png


amc-trailing-10.png
 

Pensar

Well-known member
VIP
@azakusa Thanks for the screenshots. After looking at the code, I believe I used a wrong function ( "HighestAll()" vs "LowestAll()" ), so I have updated the above code in post #2. See if it gives better results.
Also, here is what I checked it on, both before and after the code change -

/ES - 3.91% before, 4.09% after
AMC - 2.67% before, 4.5% after
AAPL - 3.94% before, 4.1% after
QQQ - 3.93% before, 4.04% after
ZM - 3.97% before, 4.12% after
GHSI - 3.63% before, 4.35% after
ASRT - 3.76% before, 4.35% after
CDEV - 3.32% before, 4.16% after
 

azakusa

New member
@Pensar

Seems using LowestAll creates too much % gap to use comfortably. Will stick with the HighestAll version.

Too bad this doesnt work accurately. It would be an amazingly helpful tool if it were precise.

Again, thanks for your help. I really appreciate it.
 

azakusa

New member
@Pensar

Just noticed your last message. Updated the script and its better, but still not plotting the 4% accurately when I jump from ticker to ticker on the 1min. Great work either way. Thanks tons.
 

azakusa

New member
Hi @Pensar,

Got to thinking... would it be possible to script a dynamic plot line at -4% of the close of the previous candle (for use on the 1 min)?
No need for the script to contain the additional current price plot, as that can run in a separate script, and no need for it to move in real-time.

Might this work effectively?
 

azakusa

New member
Hi @Pensar,

Would it be more effective to plot a static -4% line as opposed to a dynamic one? Plotting -4% of the close of the previous candle on the 1 minute chart? Happy to paypal you for your time. Thanks.
 

azakusa

New member
@Pensar

Many thanks for trying. Seems rather odd that a simple script calc which should be so straightforward doesnt work reliably. I think its no accident that this is the case.

On a side note, I have been using TOS nearly 10 years and have thought MANY times that the app is designed to screw trader.

For instance, consider the AT ladder and how it suddenly jumps to and from fractional $ amounts (1000ths sometimes) as soon as a stock gets moving, then flips to perfect round number ONLY when the stock has low volumes and is dangerous, then as soon as it gets moving flips back to fractionals. Then rejects the trade when you limit in. I mean if I cant enter using the fractional amount shown, they why the F is showing fractionals in AT at all? To force you to market order in is why (TDs little slippage game).

I am convinced that their breaking instruments down to the 1000ths this way is their replacement method of extracting probably far more $ than when they charged transaction fees. After they dumped trade fees I noticed fractionals starting to appear in the price ladder in AT.

Lastly the reason that I wanted to make this 4% line in the first place is that when you have a bracket template setup in AT and you roll over the price you want to enter at, you can only see a buy line in the chart, but not the target or the stop line. Why is that I wonder.... Most likely because they dont want you to see it.

AAARGHH..

Thanks for all your help.
 

tradecombine

New member
The sma method is clean 'cause it only looks at the recent bar.
HighestAll is not recommended by ThinkOrSwim (infer that LowestAll wouldn't be recommended, either):

Per
https://tlc.thinkorswim.com/center/...dvanced/Chapter-12---Past-Offset-and-Prefetch

We strongly recommend that you use the “IsNaN + future offset” method for detection of the last bar, not the popular HighestAll method
...
may result in productivity problems. Besides, the re-calculation mode will be set to once per bar instead of once per quote, which may also affect the output in an unwanted way. Should you need to fix the last bar in your script, use the future offset version

The code below draws three lines: most recent close, 4% above, and 4% below. You can comment out the "above_line" if you don't need it.
The -1 for the lineLength allows the line to appear in the right expansion area of your chart, so it doesn't cover up your bars/candles. Set it to 0 or a positive number if you want to cover up your candles. I have a decimal in the percent offset, so you can use numbers like 1.53% or 3.8% (I think thinkscript sets the variable type based on how input is formatted ... I'd have to re-check the tutorial to be sure.)

Code:
# Study to plot line at percent
# 02/24/2021 - Pensar original version
# 02/25/2021 - Pensar modified logic, there is now a HighestAll and LowestAll
# 03/21/2021 - modified by tradecombine, use future offset instead of HighestAll or LowestAll


input price = close;
input percentoffset = 4.0;
# putting lineLength at -1 will place the line in the right expansion area of your chart)
input lineLength = -1;

def lastBar = !IsNaN(close) && IsNaN(close[-1]);
def lastClose = if lastBar then close else lastClose[1];

plot level_line = if IsNaN(close[-lineLength-1]) then lastClose[-lineLength] else Double.NaN;
level_line.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
level_line.SetDefaultColor(Color.white);
level_line.hideBubble();

def above_price = level_line + (percentoffset/100 * level_line);
def below_price = level_line - (percentoffset/100 * level_line);

plot above_line = above_price;
     above_line.setdefaultcolor(color.white);
     above_line.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
plot below_line = below_price;
     below_line.setdefaultcolor(color.white);
     below_line.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Solution

tradecombine

New member
@Pensar

Many thanks for trying. Seems rather odd that a simple script calc which should be so straightforward doesnt work reliably. I think its no accident that this is the case.

On a side note, I have been using TOS nearly 10 years and have thought MANY times that the app is designed to screw trader.

For instance, consider the AT ladder and how it suddenly jumps to and from fractional $ amounts (1000ths sometimes) as soon as a stock gets moving, then flips to perfect round number ONLY when the stock has low volumes and is dangerous, then as soon as it gets moving flips back to fractionals. Then rejects the trade when you limit in. I mean if I cant enter using the fractional amount shown, they why the F is showing fractionals in AT at all? To force you to market order in is why (TDs little slippage game).

I am convinced that their breaking instruments down to the 1000ths this way is their replacement method of extracting probably far more $ than when they charged transaction fees. After they dumped trade fees I noticed fractionals starting to appear in the price ladder in AT.

Lastly the reason that I wanted to make this 4% line in the first place is that when you have a bracket template setup in AT and you roll over the price you want to enter at, you can only see a buy line in the chart, but not the target or the stop line. Why is that I wonder.... Most likely because they dont want you to see it.

AAARGHH..

Thanks for all your help.
@azakusa

One problem I had when first testing ThinkOrSwim was not finding a way to quickly and accurately enter bracket orders with a defined stop, target, and entry point. I found myself choosing "Market" 'cause it'd take too long to manually calculate what I wanted. Even in back-testing, I found the slippage of entering at market unacceptable. I would also realize that my quick-guessing at values would would sometimes be way off, unless I would use simple multiples like 1000 or 2000.

Using a position sizing calculator, you can basically pre-load your quantity and order parameters in a bracket, and then you just have to find your entry point on the ladder once you are close to the situation that would trigger your deal. This should save you manual calculation time and get you entering deals much faster. (Ideally, I wish the platform would support you specifying your own risk, say if 1 % of your account as a stop-loss, and then it automatically sets the order quantity based on where you set your stop when you initiate the order. This way, you can set your per-trade risk, and it'll automatically modify the number of shares purchased for the stop you set, and also automatically calculate the reward ratio. This would be much better for me, but that's not the case, so I wind up using a calculator. An end user can dream though, right?

If you could benefit from a calculator displaying values on-chart, you might want to check out the Position Sizing Calculator thread, here:
https://usethinkscript.com/threads/position-size-calculator-for-thinkorswim.588/


One thing that might help with the ladder, is the Zoom In and Zoom Out functions (if you have problems seeing all your values at once).
https://tlc.thinkorswim.com/center/howToTos/thinkManual/Trade/Active-Trader/AT-Ladder
Price displays the price breakdown; prices in this column are sorted in descending order and have the same increment equal, by default, to the tick size. You can change this increment by clicking
zoomin.2019-12-13-07-40-39
zoomout.2019-12-13-07-40-39
(Zoom In/ Zoom Out) buttons in the control bar to the right of the table.

See the link below:

Image of Zoom In and Zoom Out on Active Trader
 

azakusa

New member
Greetings @tradecombine,

Many many thanks for the suggestions and the code fix.

So far the persistent 4% calc line is dead on. Very nice!

As per your suggestion, I've set up a trade calc as a label to guide the entry process. A huge improvement! Seems its as elegant as its going to get with TOS.

Looking forward to using the script.

Best regards.
 

Similar threads

Top