Position Size Calculator for ThinkorSwim

Hey friends, I'm wondering if it is possible to reference a stop loss that has been set. I'm trying to figure out a way to do this to complete a risk to reward calculator I'm working on at the moment.

Once I'm in a trade ideally the calculator will use the stop loss that has been set to calculate 2:1 and 3:1 R:R levels and display total risk and potential profit. Currently I have to manually enter the stop loss level for each stock to get these calculations. This works great for evaluating when to enter a trade, but once I'm I'm in the trade I would prefer the calculation to work off the stop loss I have actually set for the ticker.

The only thing holding me up is that I can't seem to find any way to reference a stop loss level that has been set just like it can reference things like average price or the quantity of shares you own. Any help is very much appreciated!
 
Hey friends, I'm wondering if it is possible to reference a stop loss that has been set. I'm trying to figure out a way to do this to complete a risk to reward calculator I'm working on at the moment.

Once I'm in a trade ideally the calculator will use the stop loss that has been set to calculate 2:1 and 3:1 R:R levels and display total risk and potential profit. Currently I have to manually enter the stop loss level for each stock to get these calculations. This works great for evaluating when to enter a trade, but once I'm I'm in the trade I would prefer the calculation to work off the stop loss I have actually set for the ticker.

The only thing holding me up is that I can't seem to find any way to reference a stop loss level that has been set just like it can reference things like average price or the quantity of shares you own. Any help is very much appreciated!
We don't have a way to access such data so the short answer is, No, it can't be done from within the TOS platform...
 
Hi,

I've read a couple of position sizer threads on the site, but I'm actually looking for something simpler than what I've seen. I just want to know how many shares to buy based on the current price. I'm not concerned about the stops or limits or moving averages; I just want a label to calculate the number of shares to buy at the current price, based on the dollar limit I've set. So if I set my max dollars to spend to $100, and the stock is hovering around $5.00, it will round to 20 shares based on common rounding rules.

If I made $50 profit one day, then I'd be able to increase my dollar limit to $100.50 of stocks the next day, so I'd like to be able to easily change that amount in the script's dialogue box.

This seems simple, but is it possible?

By the way, I know that the buying dialogue area at the bottom of the page allows us to put in dollar amounts by cycling through the three circles to the left of the quantity box, but I mostly use ActiveTrader and didn't see that functionality the last time I looked. So if anyone knows how to buy based on dollar limit in ActiveTrader, it would accomplish what I'm looking for here and I wouldn't need a table to provide the information.

Thanks in advance for any help provided.

Regards,
Jason
 
@CDJay I think this should be able to fulfil your request.

Code:
# Simple Position Calculator
# Assembled by BenTen at UseThinkScript.com

input balance = 1000;
def current_price = close;
def limit = balance / current_price;
AddLabel(yes, Concat("Shares available for purchase = ", Round(limit)), color.orange);
 
@GetRichOrDieTrying- in your post #12 you wrote an excellent post on the importance of risk management and reviewed a risk management indicator from easycators.com . It certainly appears to be a well put together indicator. You mentioned you are friendly with the creator. Do you think he might be willing to offer a special pricing for members here. Kind of a deal you can't refuse. Let us know if you think this might be possible.
 
Code:
#Portfolio Risk Position Sizing

#by SparkyFlary

#This indicator shows how many shares of each inputted equity to buy to create a portfolio equally weighted based on volatility. The accountValue is how much capital there is in the account to spend, the riskPercent is how much of that account to spend on equity as a starting point(usually left alone), the volatilityLength is the length of the relative standard deviation or otherwise known as coefficient of variation that will be used to divide each equity based on volatility(the more volatile the less capital will be put into it), the choice input is whether to show the indicator values as number of shares to be bought or the total value of capital for each of those shares.

#There are 10 inputs for equity sources. They can be left blank if not all will be used. If more than 10 are needed, you will have to add more manually to this script below by simply adding more to the variables that have sequences, 1,2,3..,9,10 etc.

#When the indicator is displayed on the lower chart, make sure the mouse is navigated towards the last candle before writing down the numbers or taking a screenshot using the PrtScr button on the keyboard and pasting unto Paint or a similar program to see the screenshot. Hover the mouse towards the top of the indicator to see the rest of the outputs if not enough space.

#Make sure the outputs don't show a zero value otherwise it error'd, not sure why, maybe it's a thinkoswim issue or something. A fix is usually to just see a chart of the equity with 0 value and then check if the plot is ok, but it'll probably show a result a bit different than Tradinview.

declare lower;

input accountValue = 2000;
input riskPercent = 0.1;
input volatilityLength = 80;
input choice = {default "numOfShares", "valueOfShares"};
input src1 = "spy";
input src2 = "gld";
input src3 = "";
input src4 = "";
input src5 = "";
input src6 = "";
input src7 = "";
input src8 = "";
input src9 = "";
input src10 = "";

script COV_ {
    input price = close;
    input length = 80;
    def dev = StDev(price, length);
    def avg = SimpleMovingAvg(price, length);
    def cov = 100 * (dev / avg);
    plot scan = cov;
}

def price1 = if src1=="" then 0 else close(src1);
def price2 = if src2=="" then 0 else close(src2);
def price3 = if src3=="" then 0 else close(src3);
def price4 = if src4=="" then 0 else close(src4);
def price5 = if src5=="" then 0 else close(src5);
def price6 = if src6=="" then 0 else close(src6);
def price7 = if src7=="" then 0 else close(src7);
def price8 = if src8=="" then 0 else close(src8);
def price9 = if src9=="" then 0 else close(src9);
def price10 = if src10=="" then 0 else close(src10);

def volatility1 = COV_(price1, volatilityLength);
def volatility2 = COV_(price2, volatilityLength);
def volatility3 = COV_(price3, volatilityLength);
def volatility4 = COV_(price4, volatilityLength);
def volatility5 = COV_(price5, volatilityLength);
def volatility6 = COV_(price6, volatilityLength);
def volatility7 = COV_(price7, volatilityLength);
def volatility8 = COV_(price8, volatilityLength);
def volatility9 = COV_(price9, volatilityLength);
def volatility10 = COV_(price10, volatilityLength);

def sv1_ = (accountValue * riskPercent / 100) / volatility1;
def sv2_ = (accountValue * riskPercent / 100) / volatility2;
def sv3_ = (accountValue * riskPercent / 100) / volatility3;
def sv4_ = (accountValue * riskPercent / 100) / volatility4;
def sv5_ = (accountValue * riskPercent / 100) / volatility5;
def sv6_ = (accountValue * riskPercent / 100) / volatility6;
def sv7_ = (accountValue * riskPercent / 100) / volatility7;
def sv8_ = (accountValue * riskPercent / 100) / volatility8;
def sv9_ = (accountValue * riskPercent / 100) / volatility9;
def sv10_ = (accountValue * riskPercent / 100) / volatility10;

def sv1 = if isNaN(sv1_) then 0 else sv1_;
def sv2 = if isNaN(sv2_) then 0 else sv2_;
def sv3 = if isNaN(sv3_) then 0 else sv3_;
def sv4 = if isNaN(sv4_) then 0 else sv4_;
def sv5 = if isNaN(sv5_) then 0 else sv5_;
def sv6 = if isNaN(sv6_) then 0 else sv6_;
def sv7 = if isNaN(sv7_) then 0 else sv7_;
def sv8 = if isNaN(sv8_) then 0 else sv8_;
def sv9 = if isNaN(sv9_) then 0 else sv9_;
def sv10 = if isNaN(sv10_) then 0 else sv10_;

def count = Floor(accountValue / (sv1 + sv2 + sv3 + sv4 + sv5 + sv6 + sv7 + sv8 + sv9 + sv10));

def shareValue1 = sv1 * count;
def shareValue2 = sv2 * count;
def shareValue3 = sv3 * count;
def shareValue4 = sv4 * count;
def shareValue5 = sv5 * count;
def shareValue6 = sv6 * count;
def shareValue7 = sv7 * count;
def shareValue8 = sv8 * count;
def shareValue9 = sv9 * count;
def shareValue10 = sv10 * count;

def numOfShares1 = shareValue1 / price1;
def numOfShares2 = shareValue2 / price2;
def numOfShares3 = shareValue3 / price3;
def numOfShares4 = shareValue4 / price4;
def numOfShares5 = shareValue5 / price5;
def numOfShares6 = shareValue6 / price6;
def numOfShares7 = shareValue7 / price7;
def numOfShares8 = shareValue8 / price8;
def numOfShares9 = shareValue9 / price9;
def numOfShares10 = shareValue10 / price10;

#def totalSharesBought = shareValue1 + shareValue2 + shareValue3 + shareValue4 + shareValue5 + shareValue6 + shareValue7 + shareValue8 + shareValue9 + shareValue10;

#def totalCost = numOfShares1 + numOfShares2 + numOfShares3 + numOfShares4 + numOfShares5 + numOfShares6 + numOfShares7 + numOfShares8 + numOfShares9 + numOfShares10;

#def capitalLeftover = accountValue - totalCost;

def pick;
switch (choice) {
case numOfShares:
    pick = 0;
case valueOfShares:
    pick = 1;
}

#plot leftover = accountValue - totalValue;
plot plot1 = if pick == 0 then numOfShares1 else shareValue1;
plot plot2 = if pick == 0 then numOfShares2 else shareValue2;
plot plot3 = if pick == 0 then numOfShares3 else shareValue3;
plot plot4 = if pick == 0 then numOfShares4 else shareValue4;
plot plot5 = if pick == 0 then numOfShares5 else shareValue5;
plot plot6 = if pick == 0 then numOfShares6 else shareValue6;
plot plot7 = if pick == 0 then numOfShares7 else shareValue7;
plot plot8 = if pick == 0 then numOfShares8 else shareValue8;
plot plot9 = if pick == 0 then numOfShares9 else shareValue9;
plot plot10 = if pick == 0 then numOfShares10 else shareValue10;

I would like to share with everyone what I think might be a good way to diversify a portfolio based on the volatility of the stock rather than just putting in an equal amount of money into each stock. It's an idea I thought up while looking at risk and portfolio management formulas out there. Hopefully I did it right. If not, please let me know, or some suggestions would be nice.
Edit: I put a 2 by mistake on the share count where it should be 3, can't believe I didn't see that. Btw, the idea is similar to that of those formulas that use the distance from the stop in the denominator, except the stop in this case is the moving average but in percentage to show relative volatility.
Edit2: Rename and re-organized. It seems there's a bug where one of the plots would end up showing 0 sometimes, maybe Thinkorswim doesn't like looking are other stock values in one indicator? Tradingview doesn't seem to have this issue.
 
Last edited:
For those who find it nearly impossible to read the notes only provided in the script code, here is a more readable version...


#This indicator shows how many shares of each inputted equity to buy to create portfolio equally weighted based on volatility. The accountValue is how much capital there is in the account to spend, the riskPercent is how much of that account to spend on equity as a starting point(usually left alone), the volatilityLength is the length of the relative standard deviation or otherwise known as coefficient of variation that will be used to divide each equity based on volatility(the more volatile the less capital will be put into it), the choice input is whether to show the indicator values as number of shares to be bought or the total value of capital for each of those shares.

#There are 10 inputs for equity sources. They can be left blank if not all will be used. If more than 10 are needed, you will have to add more manually to this script below by simply adding more to the variables that have sequences, 1,2,3..,9,10 etc.

#When the indicator is displayed on the lower chart, make sure the mouse is navigated towards the last candle before writing down the numbers. Hover the mouse towards the top of the indicator to see the rest of the outputs if not enough space.
 
Last edited:
input capital_size = 25000; input risk_percent = 1; def risk_price = close; def risk_percent_calc = risk_percent / 100; def entry_stop_bull = (risk_price - bullstop); def entry_stop_bear = (bearstop - risk_price); def units_to_buy_bull = (risk_percent_calc * capital_size) / (entry_stop_bull) / risk_price; def units_to_buy_bull1 = RoundDown(units_to_buy_bull,0); def total_cost_bull = units_to_buy_bull1 * risk_price; def units_to_buy_bear = (risk_percent_calc * capital_size) / (entry_stop_bear) / risk_price; def units_to_buy_bear1 = RoundDown(units_to_buy_bear,0);
I appreciate your post and was looking to use it but just I received the following errors when I tried to use your code.

No such variable: bearstop at 7:24
At least one plot should be defined
No such variable: bullstop at 6:37
No such variable: bearstop at 7:24

Any advice will be appreciated!
 
@QUIKTDR1 What a mess of code...!!! I'll try formatting it properly and see what may be going wrong...

Edited to add: Reformatted and wondering where your bullstop and bearstop came from as they were never defined...???

Ruby:
input capital_size = 25000; 
input risk_percent = 1;
                                                           
def risk_price = close;
def risk_percent_calc = risk_percent / 100;
def entry_stop_bull = (risk_price - bullstop);
def entry_stop_bear = (bearstop - risk_price);
def units_to_buy_bull = (risk_percent_calc * capital_size) / (entry_stop_bull) / risk_price;
def units_to_buy_bull1 = RoundDown(units_to_buy_bull,0);
def total_cost_bull = units_to_buy_bull1 * risk_price;
def units_to_buy_bear = (risk_percent_calc * capital_size) / (entry_stop_bear) / risk_price;
def units_to_buy_bear1 = RoundDown(units_to_buy_bear,0);
 
Last edited:
@QUIKTDR1 What a mess of code...!!! I'll try formatting it properly and see what may be going wrong...

Edited to add: Reformatted and wondering where your bullstop and bearstop came from as they were never defined...???

Ruby:
input capital_size = 25000;
input risk_percent = 1;
                                                        
def risk_price = close;
def risk_percent_calc = risk_percent / 100;
def entry_stop_bull = (risk_price - bullstop);
def entry_stop_bear = (bearstop - risk_price);
def units_to_buy_bull = (risk_percent_calc * capital_size) / (entry_stop_bull) / risk_price;
def units_to_buy_bull1 = RoundDown(units_to_buy_bull,0);
def total_cost_bull = units_to_buy_bull1 * risk_price;
def units_to_buy_bear = (risk_percent_calc * capital_size) / (entry_stop_bear) / risk_price;
def units_to_buy_bear1 = RoundDown(units_to_buy_bear,0);


I've added a bearstop and bullstop , stopMultiple, ATR-based stop, and added slippage to your entry price.
the slippage and stop multiple are currently set to 0, so they're non-factors (you can modify them as inputs)
double-check the logic (i could be going in the wrong direction for the bull and bear offsets)
Code:
input capital_size = 25000;
input risk_percent = 1.0;
input rewardRatio = 2.0;
input stopMultiple = 0.0;
input slippage = 0.00;
input atrLength = 14;


def atrValue = ExpAverage(high - low, atrLength);
def offset = (stopMultiple * atrValue);
def bullstop = low - offset;
def bearstop = high + offset;
def risk_price = close;
def risk_percent_calc = risk_percent / 100;
def entry_stop_bull = (risk_price - bullstop);
def entry_stop_bear = (bearstop - risk_price);
def entry_limit_bull = rewardRatio * (risk_price - bullstop);
def entry_limit_bear = rewardRatio * (bearstop - risk_price);
def units_to_buy_bull = (risk_percent_calc * capital_size) / (entry_stop_bull) / risk_price;
def units_to_buy_bull1 = RoundDown(units_to_buy_bull,0);
def total_cost_bull = units_to_buy_bull1 * risk_price;
def units_to_buy_bear = (risk_percent_calc * capital_size) / (entry_stop_bear) / risk_price;
def units_to_buy_bear1 = RoundDown(units_to_buy_bear,0);
def total_cost_bear = units_to_buy_bear1 * risk_price;
def entry_price_bull = risk_price + slippage;
def entry_price_bear = risk_price - slippage;

AddLabel(
    yes,
    "BULL: " +
    "Cost: " +
    AsDollars(total_cost_bull) +
    " QTY: " +
    units_to_buy_bull1 +
    " TP: " +
    AsText(entry_limit_bull, NumberFormat.TWO_DECIMAL_PLACES) +
    " SL: " +
    AsText(entry_stop_bull, NumberFormat.TWO_DECIMAL_PLACES) +
    " Entry: " +
    AsText(entry_price_bull, NumberFormat.TWO_DECIMAL_PLACES),
    Color.GREEN
    );

AddLabel(
    yes,
    "BEAR: " +
    "Cost: " +
    AsDollars(total_cost_bear) +
    " QTY: " +
    units_to_buy_bear1 +
    " TP: " +
    AsText(entry_limit_bear, NumberFormat.TWO_DECIMAL_PLACES) +
    " SL: " +
    AsText(entry_stop_bear, NumberFormat.TWO_DECIMAL_PLACES) +
    " Entry: " +
    AsText(entry_price_bear, NumberFormat.TWO_DECIMAL_PLACES),
    Color.RED
    );



Note: in the current state, it will continually updates values as the candles are drawn. Is that what you want?

If not, then you can use [1] to base values on the prior candle:

Example, to get the current bear stop:
Code:
AsText(entry_stop_bear, NumberFormat.TWO_DECIMAL_PLACES)

To get the bear stop from prior candle:
Code:
AsText(entry_stop_bear[1], NumberFormat.TWO_DECIMAL_PLACES)

Disclaimer: Don't take trading advice from a piece of farm equipment.
 
UohgKgB.png

Can anybody help me to achieve this?
 
@yadnesh88 This thread might be what you're looking for... Position Size Calculator
Hi Alex, thank you for pointing to the post. I have already gone through the post.

I don't see if anybody using previous HL as stop loss. The paid position sizer someone mentioned also has no configuration to use HL (2, as shown in fig) as stop loss.

As I started working it, it looks easy to get current bar low and calculate position size..

But Is there any way to get HL? as shown in fig my post, want to get low of the bar at 2.
 
@yadnesh88 Is that a daily chart, intraday, or other...??? I'm assuming your reference to HL is intended to mean High and Low of current candle and Low of the previous candle... Clarity goes a long way... No need for abbreviations... We need accurate semantics in order to come up with proper syntax...
 
@yadnesh88 Is that a daily chart, intraday, or other...??? I'm assuming your reference to HL is intended to mean High and Low of current candle and Low of the previous candle... Clarity goes a long way... No need for abbreviations... We need accurate semantics in order to come up with proper syntax...
Hi Rad14733, sorry for confusion, I had to be more precise.

I am using 5 min chart.
If current bar is bull bar then I am looking to go long.
If current bar is bear bar then I am looking to go short.

For long stop loss will go below recent higher low (HL).
For Short Stop Loss will go below recent lower high (LH)

Green mark is entry point and Red is Stop Loss in below fig.

Example of long entries and recent higher low as stop loss.
fhC2huy.png


Example of short entries and recent Lower High as stop loss.
tZKWMKG.png

To simply put this, I am looking find recent higher low in uptrend and lower high in down trend as stop loss.

Once I get higher low then want to find position size from current candle high for long and vice as versa for short.
 
Last edited:
  • Like
Reactions: LIA
Is there anyway to make custom chart label that will display an approximate amount of shares I need to buy based on how much I'm willing to spend per trade as the price fluctuates?
 
@Kristen0419 Not totally sure this is what you are asking. I trade in $5000 lots so to calculate the #of shares to buy is:
Ruby:
input showshares = yes ;
input TotalDollars = 5000 ;
def tradesize = TotalDollars / close;
AddLabel(showshares, "# of shrs: " +tradesize, color.blue);
If you search this forum for position size or trade size there are many other examples
HTH
 

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
419 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