thinkScript Get EntryPrice() Function

Does anyone know if the EntryPrice() function works with lower Floating P&L study's that reference a custom strategy? I'm working on a custom Floating PL to allow for more comprehensive backtesting of strategies. Ideally, this would be setup as a lower indicator so that it can be used with any strategy (upper indicator). The problem i'm facing is that in order to handle some of the calculations I need to use the EntryPrice() of the current strategy position. After some testing, I found that the EntryPrice only seems to work when used within the upper strategy itself, as opposed to a lower study (see screenshot below). Is this expected behavior? If so, is anyone aware of any workarounds that would allow me to get the strategy EntryPrice when using the FPL function in a lower study?

1fyLkWj.png


Not possible. EntryPrice() can only be used within an upper study as a strategy.

See the following thread for workarounds: https://usethinkscript.com/threads/extended-floating-profit-loss-backtesting-data-utility.1624/
 
How would i set a static price at the time of order entry when creating a strategy. I'm looking to take the EntryPrice() - previous swing low value at the time of entry to help me create a profit target. What i'm noticing is that if there is an uptrend, it will constantly take the most recent swing low and it'll take me out of the trade early before the initial profit target is met.

I've tried:
def ExitpriceProfit_Long = high > (EntryPrice() + (EntryPrice() - pll)); #pll is equal to previous lower low.
I've tried to use rec pll thinking it would hold it as a constant at the time but doesn't seem to.

Any ideas?
 
Last edited:

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

You can maintain a constant by doing something along the lines of:

1. set ExitPriceProfit_Long to Double.NaN if there is no EntryPrice()
2. set ExitPriceProfit_Long to ExitPriceProfit_Long[1] if it is not a double.nan

I put together something that does that sort of thing here:
https://usethinkscript.com/threads/show-trades-on-thinkorswim-chart-screen.1857/post-17158
You may be able to mod it to plot your exit price instead of the entry price.

There are LOADS of caveats with this, some of which are explained in the referenced thread.

Perhaps this is a start, maybe it gets you thinking in a productive direction. Perhaps not. :)

Happy Trading,
-mashume
 
I am working a money management strategy that uses 1xATR at the entry candle for TP and 1.5xATR at the entry candle for SL. I have not been successful in figuring out how to save that value in ThinkScript as the ATR adjusts. Does anyone have some good ideas?
 
Last edited:
@GreySpecter

The method I've worked with is to define your TP and SL as double.nan when the code initializes, but with a conditional statement that says, in essence:
if there is a value here, use that value otherwise use NaN
so that when your buy signal is triggered, say by a crossover, you put a value into TP and SL. The only time there will be a value in those two is when you are inside a trade. when you exit the trade, you put NaNs back into them.
If that doesn't make any sense to you, I can try to code up something if you have some trigger conditions you can share for entry and exit.

On an aside, I'm not huge on Risk:Reward ratios, but it seems that 1x price target and 1.5x stop loss works against you on the R:R rather severely. Unless I'm reading something poorly (always an option Monday pre-coffee).

Happy trading,
mashume
 
@mashume
Thank you for the response. I may not fully understand what you are talking about, but I will post my attempt to code your suggestion. The part that I added to an HMA crossover strat is denoted by the comment. I only did a test with the LongTP, the others are just placeholders. The issue I have with this version is that the TP adjusts with every candle as the ATR adjusts.

Code:
input Price = close;
input Length = 20;
input Displace = 0;

plot HMA = HullMovingAvg(Price, Length, Displace);
plot Long = close crosses above HMA;
plot Short = close crosses below HMA;

#Custom Code Start
def ATR = ATR(14);
plot LongTP = if EntryPrice() then EntryPrice() + ATR else Double.NaN;
plot LongSL = Double.NaN;
plot ShortTP = Double.NaN;
plot shortSL = Double.NaN;

Long.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Long.SetDefaultColor(GetColor(1));
Short.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
Short.SetDefaultColor(GetColor(2));
LongTP.SetPaintingStrategy(PaintingStrategy.DASHES);
LongTP.SetDefaultColor(GetColor(1));

AddOrder(OrderType.BUY_TO_OPEN, Long, tickColor = GetColor(1), arrowColor = GetColor(1));
AddOrder(OrderType.SELL_TO_CLOSE, high >= LongTP, tickColor = GetColor(1), arrowColor = GetColor(1));
#Custom Code End

HMA.DefineColor("Up", GetColor(1));
HMA.DefineColor("Down", GetColor(0));
HMA.AssignValueColor(if HMA > HMA[1] then HMA.Color("Up") else HMA.Color("Down"));

Regarding the 1:1.5 ratio, if it is a 50% win rate, you are very correct that it is not profitable. But it often hits the 1xATR TP before it hits the 1.5xATR SL. I also close the trade if one of my primary indicators gives an opposing signal. I am currently working toward a 70% win rate on my algorithm while taking 50% profit at 1xATR and setting SL to breakeven, allowing runners to grab the rest of the profit on big moves. This would be using the daily chart in Forex.
 
Code:
def LTP = if EntryPrice() then
                if isNan(EntryPrice()[1]) then
                    EntryPrice() + ATR
                else LTP[1]
            else double.NaN;
plot LongTP = LTP;

I'm not certain this is exactly right, but the idea is this:
1. if there is an entryPrice, then there is a trade open so we want to do something
2. if this is the first bar for which there is an EntryPrice (and this is what I'm not sure is correct) then we want to use the entry Price + ATR
3. but if this isn't the first bar that there is an entry price for (the trade has been open longer than this bar) then we use the value from last time

Or something like that. :cool:

Happy trading,
Mashume
 
Can somebody please point me to some average price position line upper study indicators? I tried searching, but just could not turn up a result. Thanks!
 
Last edited by a moderator:
Looking for the same ... Some results on search >> https://futures.io/thinkorswim/34640-show-average-position-chart.html

Code:
def averagePrice=GetAveragePrice();
plot AverageTradePrice=if(averagePrice > 0, averagePrice, double.NaN);

Still mucking with it. and can't get it to work.


Or perhaps something in this code >> http://box5176.temp.domains/~markexm8/dev/forums/topic/track-your-positions-on-your-charts/

Code:
*********START COPY AND PASTE ON NEXT LINE******************

# CDC_Position
input Name = “©<2018>_Position”;
input ShowName = no;

######################################################################################
# DISPLAY LABEL FOR COMPARISONS
######################################################################################

AddLabel(ShowName, Name, CreateColor(15, 125, 15));

#
# TD Ameritrade IP Company, Inc. (c) 2011-2018
# Copyright (c) © <2017-2018> <Clarence Carr>
#
# All Rights Reserved.:
#
#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
#
Input ShowPosition = yes;
Input ShowPositionDetails = yes;

def Totqty = GetQuantity();
def openCost = Totqty * GetAveragePrice();
def netLiq = Totqty * close;
def netliqpercent = (NetLiq-NetLiq[1])/NetLiq[1];
Def Display = If (GetAggregationPeriod()==AggregationPeriod.Week or GetAggregationPeriod() ==AggregationPeriod.Month or GetAggregationPeriod() ==AggregationPeriod.OpT_EXP) or !ShowPositionDetails then no else yes;

plot PurchasePrice = if GetAveragePrice() == 0 then Double.NaN else GetAveragePrice();
PurchasePrice.AssignValueColor(If Totqty >0 then Color.DARK_ORANGE else Color.Blue);
PurchasePrice.SetLineWeight(3);
PurchasePrice.SetPaintingStrategy(PaintingStrategy.Line);
#PurchasePrice.SetHiding(!Display);

#plot ManualOpenPL = netLiq – openCost;
def AutoOpenPL = GetOpenPL();

#AddLabel(Totqty and Display, “Qty: ” + Totqty + ” AvgPrice: <b>” + Round(PurchasePrice,2) + “</b> NetLiq: ” + AsDollars(Round(NetLiq,2)) + ” TotCost: “+ Round(openCost,2) +” TodayPL: ” + AsDollars(AutoOpenPL – AutoOpenPL[1])+ ” OpenPL: <b>” + AsDollars(Round(AutoOpenPL,2)) + </b>”,Color.Dark_Gray);
AddLabel(Totqty<0 and ShowPosition, “SHORT QTY: ” + Totqty + ” @” + AsDollars(Round(PurchasePrice, 2))+” NetLiq: ” + AsDollars(Round(NetLiq,2)),Color.Blue);
AddLabel(Totqty>0 and ShowPosition, “LONG QTY: ” + Totqty + ” @” + AsDollars(Round(PurchasePrice, 2))+” NetLiq: ” + AsDollars(Round(NetLiq,2)) ,Color.Dark_Orange);

AddLabel(Totqty and Display, ” AvgPrice: ” + AsDollars(Round(PurchasePrice, 2)) , IF AutoopenPL >=0 then Color.Dark_Green else color.Red);

AddLabel(Totqty and Display, “ThisBarPL: ” + AsDollars(AutoOpenPL – AutoOpenPL[1]) + ” OpenPL: ” + AsDollars(Round(AutoOpenPL, 2)) + ” (” + Round(((NetLiq-OpenCost)/OpenCost)*100,2)+ “%)” , IF AutoopenPL >=0 then Color.Dark_Green else color.Red);

AddLabel(ISNAN(Totqty) and Display, ” No positions currently held.”, Color.Dark_Gray);
 
Hi mashume, this line

Gets an error message: Function "EntryPrice" is not dynamic, indexer is senseless

How can we use your method to store the entry bar's ATR, instead of each new bar's ATR?
@Zara2 I think if EntryPrice()[1] is complaining that it can not be indexed, just assign to a variable and index that variable.
Just a minor tweak of @mashume code:

Code:
def myEntryPrice = EntryPrice();
def LTP = if myEntryPrice then
                if isNan(myEntryPrice[1]) then
                    EntryPrice() + ATR()
                else LTP[1]
            else double.NaN;
plot LongTP = LTP;
 
Last edited:
Can somebody please point me to some average price position line upper study indicators? I tried searching, but just could not turn up a result. Thanks!
@evanevans hopefully you found your solution already. If not, EntryPrice() returns the average entry price for a strategy.
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/EntryPrice

@tlebouef GetAveragePrice() is a portfolio function, so it only works with your "real" account info, not a strategy/backtest. Try replacing it with EntryPrice(). It would be helpful if TOS provided the same functions for strategies.
 
You can maintain a constant by doing something along the lines of:

1. set ExitPriceProfit_Long to Double.NaN if there is no EntryPrice()
2. set ExitPriceProfit_Long to ExitPriceProfit_Long[1] if it is not a double.nan

I put together something that does that sort of thing here:
https://usethinkscript.com/threads/show-trades-on-thinkorswim-chart-screen.1857/post-17158
You may be able to mod it to plot your exit price instead of the entry price.

There are LOADS of caveats with this, some of which are explained in the referenced thread.

Perhaps this is a start, maybe it gets you thinking in a productive direction. Perhaps not. :)

Happy Trading,
-mashume
hi Mashume, always glad when you step in to the discussion. Can you help me understand something. If I am developing a strategy to test will EntryPrice() take into account a point where my strategy gets long or short?
 
hi Mashume, always glad when you step in to the discussion. Can you help me understand something. If I am developing a strategy to test will EntryPrice() take into account a point where my strategy gets long or short?
So take this code with a grain or two of salt... it seems to work, but it isn't well tested and may give you completely wrong numbers, or no numbers, or it may work... use at your own risk.

EntryPrice() will return a NaN if you are not in an actual trade. It doesn't record backtesting entry prices to the best of my knowledge.

Some of this code may be helpful, though it requires you to have your buy and sell conditions elsewhere and as 1 and 0 for true and false (not something and NaN). They are not defined in this code.
Code:
def direction = if buy[1] == 1 then 1 else if sell[1] == 1 then -1 else direction[1];

def ordercount = if buy == 1 or sell == 1 then ordercount[1] + 1 else if isNan( ordercount[1]) then 0 else ordercount[1];
def close_at_trade = if buy[2] == 1 or sell[2] == 1 then open[1] else close_at_trade[1]; 

def pl_this_trade = (open - close_at_trade[1]) * (tickValue() / ticksize() ) * -direction;
def pl_at_trade = if buy[1] == 1 or sell[1] == 1 then pl_at_trade[1] + pl_this_trade else if isNan(pl_at_trade[1]) then 0 else pl_at_trade[1];

addLabel(yes, "  Current Trade Value:  " + asDollars( (open - close_at_trade[1]) * tickValue() / ticksize() * direction) + "  ", if (open - close_at_trade[1]) * tickValue() / ticksize() * direction > 0 then color.dark_green else color.dark_red);

def winning_trades = if buy[1] == 1 or sell[1] == 1 then if pl_this_trade > 0 then winning_trades[1] + 1 else winning_trades[1] else if isNan(winning_trades[1]) then 0 else winning_trades[1];

AddLabel(yes, "  order count:  " + ordercount + "  ", color.blue);
AddLabel(yes, "  ToS PL: " + FPL() + "  ", if FPL () > 0 then color.dark_green else color.dark_red);
AddLabel(yes, " PL at last trade = " + asDollars( pl_at_trade) + "  ", if pl_at_trade > 0 then color.dark_green else color.dark_red);
AddLabel(yes, "  Win % = " + asPercent( (winning_trades / ordercount)) + "  ", color.black);
AddLabel(yes, "  Average Trade Value:  " + asDollars( pl_at_trade / ordercount) + "  ", color.black);
 
So take this code with a grain or two of salt... it seems to work, but it isn't well tested and may give you completely wrong numbers, or no numbers, or it may work... use at your own risk.

EntryPrice() will return a NaN if you are not in an actual trade. It doesn't record backtesting entry prices to the best of my knowledge.

Some of this code may be helpful, though it requires you to have your buy and sell conditions elsewhere and as 1 and 0 for true and false (not something and NaN). They are not defined in this code.
Code:
def direction = if buy[1] == 1 then 1 else if sell[1] == 1 then -1 else direction[1];

def ordercount = if buy == 1 or sell == 1 then ordercount[1] + 1 else if isNan( ordercount[1]) then 0 else ordercount[1];
def close_at_trade = if buy[2] == 1 or sell[2] == 1 then open[1] else close_at_trade[1];

def pl_this_trade = (open - close_at_trade[1]) * (tickValue() / ticksize() ) * -direction;
def pl_at_trade = if buy[1] == 1 or sell[1] == 1 then pl_at_trade[1] + pl_this_trade else if isNan(pl_at_trade[1]) then 0 else pl_at_trade[1];

addLabel(yes, "  Current Trade Value:  " + asDollars( (open - close_at_trade[1]) * tickValue() / ticksize() * direction) + "  ", if (open - close_at_trade[1]) * tickValue() / ticksize() * direction > 0 then color.dark_green else color.dark_red);

def winning_trades = if buy[1] == 1 or sell[1] == 1 then if pl_this_trade > 0 then winning_trades[1] + 1 else winning_trades[1] else if isNan(winning_trades[1]) then 0 else winning_trades[1];

AddLabel(yes, "  order count:  " + ordercount + "  ", color.blue);
AddLabel(yes, "  ToS PL: " + FPL() + "  ", if FPL () > 0 then color.dark_green else color.dark_red);
AddLabel(yes, " PL at last trade = " + asDollars( pl_at_trade) + "  ", if pl_at_trade > 0 then color.dark_green else color.dark_red);
AddLabel(yes, "  Win % = " + asPercent( (winning_trades / ordercount)) + "  ", color.black);
AddLabel(yes, "  Average Trade Value:  " + asDollars( pl_at_trade / ordercount) + "  ", color.black);
fantastic, will try that. Thank you
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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