4
votes

Hey I'm trying to save the close price at the time of strategy.entry to a variable so I can use it later for an exit.

if condition
    strategy.entry("long", true)
    buyprice=close
(strategy.exit("exit","long", when = close>buyprice*1.1) 

I get the error: Undeclared identifier 'buyprice'. From what I understand this means that the variable is not valid outside of the if statement. Is there a way to change this? Thanks in advance for your help

2
declare buyprice in global scopeDeepanshu Kapoor
Why was this question protected? Just doesn't make sense...not2qubit

2 Answers

2
votes

This is the only way that I could get this to work.

Basically, you set the previous price when long condition is met and then retrieve that value from the global variables in the next phase.

//@version=2
...
buyprice=buyprice[1]


golong=...

if golong
    buyprice := close

goshort=... or close<=buyprice*0.95

strategy.entry("Long", long=true, when=golong)
strategy.close("Long", when=goshort)

Hope this helps!

0
votes

Add this AFTER to the code you use to enter a position:

bought = strategy.position_size[0] > strategy.position_size[1]
entry_price = valuewhen(bought, open, 0)