How to store a value on PineScript after an entry?

Viewed 88

I'm setting a take profit value 1:1 to the risk. It's based on ATR. Once the price closes above/below atr it gives me the entry point and after that, I calculate the distance between the entry price and the ATR. So this distance will be as same as my TP. But what happens is that the bot keeps getting the ATR level from the last bar, and not from the entry bar.

Here's the sample of the code and a screenshot of a trade:

illustration

//@version=4
buy = crossover(close,atr)
sell = crossunder(close,atr)
    
 
strategy.entry("long",   true, when = buy)
strategy.entry("short", false, when = sell)


//calculate difference between entry and atr
differenceLong = strategy.position_avg_price - atr
differenceShort = atr - strategy.position_avg_price

//Calculate the TP price

longExitPrice  = strategy.position_avg_price + differenceLong
shortExitPrice  = strategy.position_avg_price - differenceShort

if (strategy.position_size > 0)
    strategy.exit(id="TP", limit = longExitPrice)

        
if (strategy.position_size < 0)
    strategy.exit(id="TP", limit = shortExitPrice)
1 Answers

Use the built-in variable strategy.position_size to figure out if you enter a new position. Then use a var to store the ATR value at the time of the entry. By using a var, you are making sure that its value will not be updated unless you specifically do so.

atr = ta.atr(14)

var float atr_at_entry = na

is_new_long = (strategy.position_size > 0) and (strategy.position_size > strategy.position_size[1])
is_new_short = (strategy.position_size < 0) and (strategy.position_size < strategy.position_size[1])
is_new_entry = is_new_long or is_new_short

atr_at_entry := is_new_entry ? atr : atr_at_entry

Use atr_at_entry in your exit calculations.

Note: If you are using process_orders_on_close=true, you need to get the previous atr value like so: atr_at_entry := is_new_entry ? atr[1] : atr_at_entry

Related