0
Follow
2
View

How to store a value on PineScript after an entry?

dtq_1985 注册会员
2023-01-25 10:49

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