5
votes

Someone asked a similar question with no response and I am not allowed to add to it.

Tradingview Pine script save close price at time of strategy entry

I am trying to build a strategy that will buy multiple times (pyramiding) to average down before closing but I want to check the previous entry price to make sure it's less by a configured percentage.

What I have so far:

lastBuy=0

if (condition)
    if (lastBuy==0)
        lastBuy=close
        strategy.entry("buy", true)
    else
        if ((close*1.01)<lastBuy)
            lastBuy=close
            strategy.entry("buy", true)

Each time the code is passed it resets lastBuy back to zero and I never get to check the previous close price. If I don't set this I get undeclared error.

Thanks in advance for any help!

4

4 Answers

4
votes

How I am saving the entry price to a variable:

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

This works for entry price.

entryPrice = valuewhen(strategy.opentrades == 1, strategy.position_avg_price, 0)

1
votes

Each time the code is passed it resets lastBuy back to zero and I never get to check the previous close price. If I don't set this I get undeclared error.

This happens because your code tries to declare the same lastBuy variable repeatedly. Doing so gets you TradingView's undeclared identifier error.

To solve this situation, first declare your variable with =. Then update its value with :=. Just keep in mind that you can't use the = operator more than once on the same variable.

So change your code to:

lastBuy = 0

if (condition)
    if (lastBuy == 0)
        lastBuy := close
        strategy.entry("buy", true)
    else
        if ((close*1.01)<lastBuy)
            lastBuy := close
            strategy.entry("buy", true)
0
votes

The var keyword is a special modifier that instructs the compiler to create and initialize the variable only once. This behavior is very useful in cases where a variable’s value must persist through the iterations of a script across successive bars.

https://www.tradingview.com/pine-script-docs/en/v4/language/Expressions_declarations_and_statements.html

You should put "var" before "lastBuy" so it won't be reseted.

var lastBuy = 0

if (condition)
    if (lastBuy == 0)
        lastBuy := close
        strategy.entry("buy", true)
    else
        if ((close*1.01)<lastBuy)
            lastBuy := close
            strategy.entry("buy", true)