Entry, Target, Profit Loss (PnL) Watchlists, Labels of Owned Equities In ThinkOrSwim

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
Tired of flipping over to the monitor tab to see how your trade is going?

Problem solved!
Here are your P&L Labels For Charts

This script provides the P/L For Accumulated Trades
The Net PnL uses a cost adjusted basis: ProfitLossMode.COST_BASIS

These labels include
  • the total Quantity bought,
  • Average Purchase Price per share and total,
  • the Adjusted Average Sales Price per share and total
  • and the net Gain/Loss
You can edit out the fields that you don't want.
6ewhwpz.png

Ruby:
# Profit & Loss Label (on a cost adjusted basis)
# @merryday 2/2023

input PLMode = ProfitLossMode.COST_BASIS;
def PL = GetOpenPL(profitLossMode = PLMode) ;

def Entry = if GetAveragePrice() != 0 then GetAveragePrice() else Entry[1];
def GainLoss = if PL != 0 then PL else GainLoss[1];
def Qty =  if GetQuantity() != 0 then GetQuantity() else Qty[1];

DefineGlobalColor("Gain",  CreateColor(0, 165, 0)) ;
DefineGlobalColor("Loss",  CreateColor(225, 0, 0)) ;

AddLabel(GainLoss,
"Qty: " + Qty + "  Entry/shr $" + Entry + "   Exit/shr  $" + (Entry+GainLoss)
+ "  | Total Purchase: " +Qty*Entry  + "   Total Sale: " +Qty*(Entry+GainLoss)
+" | P/L: " + AsDollars(GainLoss*Qty),
      if GainLoss > 0 then GlobalColor("Gain") else GlobalColor("Loss"));
 
Last edited:
Hello,

I've put together a simple profit/loss zone indicator/study that will help with visualizing profit/loss zones. I would love to see others add/expand/improve this for automation as well as to use in range-bar setup. Here's the code, and a couple of use-cases.

The process of displaying this is very crude, but it's manual. I trade on another platform for day-trading and use TOS for visualizing, so I wanted a way to see my stop zones. The way it works is you enter a profit/loss range in $ amount. I trade using ATR, so I either use 1:1 ATR for my range, or .5:1 ATR range for tighter moves. The zones can switch between buy and sell. Yellow dotted line indicates $ figure you are in at. the plot posts at a certain time, and for a duration after, which you can extend if you like. You can switch on/off by indicating if you're in. Here are the figures:

Value: 00.00 # Use this to indicate the rage between your loss/take profit. If you believe $ will go up by $0.05, then type 0.05
dollarvalue: 0000 # Use this to indicate your dollar value. The number will divide by 100, so 4000 = 40.00 aka $40.00
Buy: yes/no #this is if you are long or short. Buy yes means long, buy no means short. Its crude but I understand it...
Thyme: 0000 # Use this to indicate time. 0630 is 06:30... 834 is 08:34.. etc
min: 0 #How many minutes you expect to sit in your trade... I use 10 or so by default depending on volitility
are you in: yes/no #show the graph or not, I had it automatic with getquantity() but again I use this for charting more than trading on TOS

The zones are 1x 2x 3x and -1x -2x, I added clouds as well just to give me a better look. I would love to use this on Range bars using ATR ranges because this is how I mainly trade, priceaction intraday. If anyone has tips to make this indicator simpler, easier, and faster, I would love that. I want to add a vertical line for time, and extend my yellow horizontal line left as well to show price... Similar to the vertical drawing/horz drawing for time/price. If I could also trigger this study every time my price/time drawings cross, that would be amazing!!!

Just Labels from the 2nd Script:
0DJaiWx.png



Profit and Loss Zones:
fw4X96e.png


YeXZ3hB.png


Code:
# Crude Buy Sell Zone indicator by ANTHDKN 06.04.2021
# Free to use to all
# First posted on usethinkscript.com
# Manual entries for positions
input value = .07;
input dollarvalue = 0;
input buy = yes;
input thyme = 0630;
input min = 2; # Mins till

def BUY_YES_SELL_NO = if buy then no else yes;
def thymeOffset = 0300;
def showAt = thyme + thymeoffset;

def avg = dollarvalue * .01;

input AreYouIn = no;

# Average True Range Label
AddLabel(!AreYouIn, "ATR: " + AsDollars(ATR()), Color.YELLOW);

# You are in Label
addlabel(areyouin, "In at " + asdollars(avg), color.white);


# Profit/Loss zones as multiple of ATR

# Sell Side

def targetprice03 = if !Buy_Yes_Sell_No
                    then (avg * .01) - (value * 3)
                    else (avg * .01) + (value * 3);
def targetprice02 = if !Buy_Yes_Sell_No
                    then (avg * .01) - (value * 2)
                    else (avg * .01) + (value * 2);
def targetprice01 = if !Buy_Yes_Sell_No
                    then (avg * .01) - (value)
                    else (avg * .01) + (value);

#Buy Side
def targetprice1 = if Buy_Yes_Sell_No
                    then (avg * .01) + (value)
                    else (avg * .01) - (value);
def targetprice2 = if Buy_Yes_Sell_No
                    then (avg * .01) + (value * 2)
                    else (avg * .01) - (value * 2);
def targetprice3 = if Buy_Yes_Sell_No
                    then (avg * .01) + (value * 3)
                    else (avg * .01) - (value * 3);

### Lines

def showLines = if AreYouIn
                then (if secondstillTime(showAt) <= 0
                      and secondsFromTime(showat) <= thymeOffset * min
                      then 1 else 0)
                else no;

plot downside2 = if showLines
                 then (if !Buy_Yes_Sell_No
                       then avg - (value*2)
                       else avg + (value*2))
                 else Double.NaN;
downside2.SetStyle(Curve.FIRM);
downside2.SetDefaultColor(Color.DARK_RED);

plot downside1 = if showLines
                 then (if !Buy_Yes_Sell_No
                       then avg - (value)
                       else avg + (value))
                 else Double.NaN;
downside1.SetStyle(Curve.SHORT_DASH);
downside1.SetDefaultColor(Color.RED);

plot avgprice = if showLines  then avg else Double.NaN;
avgprice.SetStyle(Curve.SHORT_DASH);
avgprice.SetDefaultColor(Color.YELLOW);

plot upside1 = if showLines
                 then (if !Buy_Yes_Sell_No
                       then avg + (value)
                       else avg - (value))
                 else Double.NaN;
upside1.SetStyle(Curve.SHORT_DASH);
upside1.SetDefaultColor(Color.LIGHT_GREEN);

plot upside2 = if showLines              
                then (if !Buy_Yes_Sell_No
                       then avg + (value*2)
                       else avg - (value*2))
                 else Double.NaN;
upside2.SetStyle(Curve.SHORT_DASH);
upside2.SetDefaultColor(Color.LIGHT_GREEN);

plot upside3 = if showLines
                 then (if !Buy_Yes_Sell_No
                       then avg + (value*3)
                       else avg - (value*3))
                 else Double.NaN;
upside3.SetStyle(Curve.FIRM);
upside3.SetDefaultColor(Color.DARK_GREEN);

### Clouds
AddCloud((downside1+downside2)/2, downside2,  Color.DARK_RED, Color.DARK_RED);
AddCloud(((upside1+upside3)/2), upside3, Color.DARK_GREEN, Color.DARK_GREEN);
AddCloud((downside1+downside2)/2, ((upside1+upside3)/2), Color.gray, Color.gray);

### Alerts
def SoundAlert = high crosses above upside2 or low crosses below downside1;
Alert(SoundAlert, "Something exciting just happened with " + GetSymbol(), Alert.BAR, Sound.Ring);

#AddLabel(AreYouIn,
#            "[-" + AsPercent(value*2 / TargetPrice2) + "]" +
#            ":" + AsDollars(targetprice01) +
#            " [-" + AsPercent(value / targetprice01) + "]" +
#            ":" + AsDollars(TargetPrice01),
#                if avg <= 0
#                then Color.BLACK
#                else Color.LIGHT_RED);

#AddLabel(AreYouIn, "[" + AsPercent(value / TargetPrice1) + "]:" +
#                   AsDollars(TargetPrice1) + " " +
#                   "[" + AsPercent((value * 2) / TargetPrice2) + "]:" #+
#                   AsDollars(TargetPrice2) + " " +
#                   "[" + AsPercent((value * 3) / TargetPrice3) + "]:" +
#                   AsDollars(TargetPrice3) + " ",
#                if avg <= 0
#                then Color.BLACK
#                else Color.LIGHT_GREEN);

Code:
# Crude Buy Sell Zone indicator by ANTHDKN 06.04.2021
# Free to use to all
# First posted on usethinkscript.com
# Auto entries from positions
input value = .07;
def avg = getaveragePrice();
def AreYouIn = if getquantity() != 0 then yes else no;

def targetprice02 = (avg) - (value*2);
def TargetPrice01 = (avg) - value;
def TargetPrice1 = (avg) + value;
def TargetPrice2 = (avg) + (value * 2);
def TargetPrice3 = (avg) + (value * 3);

AddLabel(AreYouIn,
 
         getquantity() +
         "@" + avg +
         "= $" +
         (avg * getquantity()),
       
         Color.WHITE);

AddLabel(AreYouIn,
         if GetOpenPL() > 0
         then "P/L: $" + GetOpenPL() + " [" +
              aspercent(getopenPL() / (avg *  getquantity())) + "]"
         else "P/L: -$" + GetOpenPL() + " [" +
              aspercent(getopenPL() / (avg *  getquantity())) + "]",
         if GetOpenPL() > 0
         then Color.DARK_GREEN
         else Color.DARK_RED);

plot downside2 = if avg != 0  then TargetPrice02 else double.nan;
downside2.setstyle(curve.FIRM);
downside2.setdefaultColor(color.DARK_RED);

plot downside1 = if avg != 0  then TargetPrice01 else double.nan;
downside1.setstyle(curve.SHORT_DASH);
downside1.setdefaultColor(color.red);

plot avgprice = if avg != 0  then avg else double.nan;
avgprice.setstyle(curve.SHORT_DASH);
avgprice.setdefaultColor(color.Yellow);

plot upside1 = if avg != 0  then TargetPrice1 else double.nan;
upside1.setstyle(curve.SHORT_DASH);
upside1.setdefaultColor(color.light_GREEN);

plot upside2 = if avg != 0  then TargetPrice2 else double.nan;
upside2.setstyle(curve.SHORT_DASH);
upside2.setdefaultColor(color.light_GREEN);

plot upside3 = if avg != 0  then TargetPrice3 else double.nan;
upside3.setstyle(curve.FIRM);
upside3.setdefaultColor(color.dark_GREEN);

#AddLabel(AreYouIn,
#            "[-" + AsPercent(value*2 / TargetPrice2) + "]" +
#            ":" + AsDollars(targetprice01) +
#            " [-" + AsPercent(value / targetprice01) + "]" +
#            ":" + AsDollars(TargetPrice01),
#                if avg <= 0
#                then Color.BLACK
#                else Color.LIGHT_RED);

#AddLabel(AreYouIn, "[" + AsPercent(value / TargetPrice1) + "]:" +
#                   AsDollars(TargetPrice1) + " " +
#                   "[" + AsPercent((value * 2) / TargetPrice2) + "]:" #+
#                   AsDollars(TargetPrice2) + " " +
#                   "[" + AsPercent((value * 3) / TargetPrice3) + "]:" +
#                   AsDollars(TargetPrice3) + " ",
#                if avg <= 0
#                then Color.BLACK
#                else Color.LIGHT_GREEN);
 
Last edited by a moderator:
Can you someone help with the setting to view the Position statement P/L in Green and Red . also if it is lose with (-) and profit with (+) symbol?

If there is an existing view or separate code available that would be much appreciated?

Thanks,
Suresh K
 
Can you someone help with the setting to view the Position statement P/L in Green and Red . also if it is lose with (-) and profit with (+) symbol?

If there is an existing view or separate code available that would be much appreciated?

Thanks,
Suresh K

It is under "Studies" called PositionOpenPL.
 
By default, for "Show trades" TOS will add a big text box such as [email protected] on top or bottom of the candle stick. If there are multiple trades on the same minute, they will overlap and be very hard to read.

For each trade, i want to just draw a small symbol (such as a up/down triangle, such as up for buy and down for sell, or other similar) at the prices at that candle on the chart. I just want to know the buy and sell places, not the share sizes.

I have been looking for similar script, but doesn't find any. Can someone help me?
 
Last edited:
This ONLY WORKS for showing purchase price if the purchase happened on the chart somewhere, i.e. in the last 5 days if the chart shows 5 days of data.
I can't seem to find position size automatically. You'll need to adjust the input of your position size to match your position (unless you have something entirely other in mind. But give this a try.

IT REQUIRES YOU TO SET THE SIZE
IT REQUIRES THE PURCHASE TO BE ON THE CURRENT CHART
AND IT DOESN"T PLOT THE PAID PRICE EXACTLY

I offer it as a starting point ONLY

I suppose you could always set your expected position size before you enter, so that it'll graph immediately.

Code:
declare upper;

# ThinkOrSwim Mobile Style Position Price Indicator
# For Desktop
# Mashume
# 2020-02-28

declare upper;

input size = 100;

def liq = positionNetLiq();
def position = liq / size;

def enter = if position != 0 then
        if position[1] == 0 then position
        else enter[1]
    else double.nan ;

plot entryPrice = enter;

It only works for securities for which the actual purchase candle appears on the chart.

Additionally, I can't get it to give me a proper calculation for the size of a position given the price when the position was opened. That is, I can get a number, round it, and it displays, graphs, etc.. properly, but I can't use it as a divisor without breaking the position calculation.
THIS DOESN"T WORK. Any ideas?
Code:
def s = if !isnan(liq) then round(liq / ((OPEN + CLOSE) / 2), numberOfDigits = 0) else double.nan;
def position = positionNetLiq() / s;

Happy Trading
Mashume
 
Last edited:
I've been trying to script a study that would add a label up in the top left corner of a chart showing this info:
  • % up or down of today's current P/L compared with yesterday's P/L (or p/l as of 11:59p yesterday)
The goal here is to potentially better recognize when daily targets or max losses are hit.

I can get the current value from "GetNetLiq()", but struggling to calculate historic account value data.

Once this is calculated, a simple equation could be done (today's pl / yesterday's pl = value I'm looking for) and then the rest of the customization would be straightforward:
  • color based on how much up or down
  • alert based on how much up or down

Thanks!
NJM
 
On a daily chart you could use GetNetLiq() [1] to get yesterdays value. However, it doesn't seem to allow using a daily aggregation on other timeframes. I thought it wasn't possible, but this great post HERE by RobertPayne shows how to still access yesterday's values. For example, this code should get you started with the values you need, and you can go from there:
Code:
def today = GetDay() == GetLastDay();
def todayNetLiq = GetNetLiq();
def yestNetLiq = if today then yestNetLiq[1] else GetNetLiq();
 
Hello, I've been trying to use my the portfolio functions available to me such as "GetAveragePrice()" or "GetOpenPL()", however all of them seem to be giving me the value N/A regardless of me being in a position or not. I checked the instructions in the learning center and my chart has the "last" price type and I was using the 1min aggregation type which is acceptable. I don't have much money in my account so I just bought one share of JDST and one share of AAL around 1 pm (I'm not sure if the time matters just want to be descriptive). Both times when I bought the account my label showed nothing. Here is the script for my label:

#Script
addLabel(yes, getAveragePrice());
# end of script
it's just that one line but all I see in my lable is N/A. Has anyone had any issues like this using portfolio actions or does anyone know what might be the problem here? Let me know if you need me to elaborate on any of the points I've made
 
@Rose Investing, I dont know much about portfolio functions in thinkscript, its something I need to learn. However, perhaps this code can help you. I found it in the thinkScript Community OneNote.

Code:
# All the Portfolio Functions in a Label
# Mobius

def GetAveragePrice = GetAveragePrice();
def GetNetLiq = GetNetLiq();
def GetOpenPL = GetOpenPL();
def GetQuantity = GetQuantity();
def GetTotalCash = GetTotalCash();

addLabel(1, "GetAveragePrice = " + GetAveragePrice +
          "  GetNetLiq = " + GetNetLiq +
          "  GetOpenPL = " + GetOpenPl +
          "  GetQuantity = " + GetQuantity +
          "  GetTotalCash = " + GetTotalCash, color.white);
 
Correct - something like this. Basically what they have on the mobile version. So i know it can be done!
Agree, this is so stupid not to have a line with the number + or - of contracts that you have as a position, which does exist in the mobile. Every other platform has it, it is so basic. I don't think TOS desktop has anything like this and its a shame, considering how much invested in this platform, not to have something as basic as your position on the chart.
 
  • Like
Reactions: RAC
Hi- Below is what I did to display my Trades on TOS chart. I hope this helps.

Check to see if advanced Features are enabled
  1. Log into TD Ameritrade
  2. Select My profile
  3. Under the general tab, make sure "Advanced Features" is set to "Enabled".
Display on Chart
  1. Click on the Gear
  2. General Tab -> Content ->Display -- Make sure "Show Trades" is checked
  3. Click "Setup" typically in the top right
  4. Save workspace as (enter your name)
  5. Close then restart TOS. I right clicked, run as ADMIN. Idk if it matters.
 
Thanks for sharing but I am confusing. Can you share with us the screen shot of your set up? My TOS is showing the working order on the chart and I did not have to do anything with this setting at all. Sorry, for some reason I can not attract the screen shot for you to see
 
I am afraid I already know the answer but in hopes that I am wrong, here is my question: Can I set up a watchlist displaying gains and losses?

The label displays correctly on my charts with no errors.

But it gives the error:

no such function getaverageprice no such function getquantity

when I attempt to load the script into a watchlist field.

Here is my custom field:
Code:
def cost = GetAveragePrice();
def qty  = GetQuantity();
def purchase = qty * cost ;
def present  =  qty * close ;
plot gainloss = present - purchase ;
gainloss.Hide();
def GLpct    = Round(gainloss / purchase, 3) ;
AddLabel(yes, "gain " + gainloss + " " + AsPercent(GLpct), if gainloss > 0 then Color.GREEN else Color.RED );

I get around the problem by keeping a detached monitor screen up. But it is a poor substitute for my watchlist which has all my stocks and sell indicators. It would be helpful to see my current gains in the field next to my sell indicators when I am making quick decisions.

How do other people get around watching all the stocks they have in play?
 
Last edited:
@MerryDay - in the watchlist 'available items' there is p/l day, p/l open, p/l percent, p/l year

On my options watchlist, my setup is - theo price, impl vol, delta, p/l open, position qty - i fond quantity most helpful as when orders get hit dont need to think about how many i have left

seems to work well
 
Thank you @codydog. I am using those fields in my watchlist along with average trade price.
I assume you are saying that I cannot use those items in calculating loss and gains the way I would like?
 
@MerryDay - not sure exactly, what you're doing, but my experience is that some folks try to shoehorn all kinds of stuff in watchlists, when a simple mental calc would solve their concerns. And i have no idea what tos resources get used for this, perhaps considering flipping this into an excel and having it update there?

I use RTD for some options stuff and it seems ok.
 
@codydog I usually have around a dozen stocks in play during the day. My holding period is anywhere from 3hrs to 3wks. I have an "Stocks in Play" watchlist w/ all the stocks I own and you are right. I shoehorn plenty into it. I have fields to alert me when they hit resistance bands, swing under or over the ATR trail, when Welkin Volume alerts, as well as labels that alert for change in zScore, Matrix slope, and IWO squeeze.

When indicators flip, I have to go to the TOS monitor and my spreadsheets to review my current position to determine profit-taking and risk assessment. I would like an "at a glance summary" all in one place.

I will chalk this up to another thing that TOS falls short on. Not knocking TOS. I have been fiddling on TradeStation; it turns out things are not always greener on the other side. Automating orders exits based on an ATR trailstop is problematic there also. I have yet to find a robust ability to track/watch gains/losses over there either. And of the most concern: I have yet to find a group that is as giving of their time and knowledge as I have enjoyed here.
 
Heeheehee... I definitely have lots of demands when it comes to watching my money. My goal is to have one place where I can see what is invested, what the current standing is, and where my indicators are pointing.

It's hard to believe that there is a greater demand for this.
It seems that many people want the holy grail to find the perfect stock to buy which is such a small part of the equation.
Stock management analysis and compound exit strategies are my keys to making a profit. It is not just TOS that falls woefully short in database portfolio analysis. My research hasn't found a trading software that is excelling in this area.

The fields are already populating the database. I have to believe that most trading systems aren't making them available because there is no demand.
We are all doing in spreadsheets, what should be easily done within the program.
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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