'Update variable at condition
I would like to update a variable (in the below example is new_profit_long) every time a condition is verified.
The following is a simplified example of what I want to achieve:
entry = nz(strategy.opentrades.entry_price(strategy.opentrades - 1))
profit = entry + tp
loss = entry - sl
extra = tp * .5
new_profit = profit
if close > profit
if close > new_profit
new_profit := new_profit + extra
else
strategy.close("long")
else if close < loss
strategy.close("long")
Unfortunately, I get this behaviour:
| close | entry | (old) new_profit | (new) new_profit | notes |
|---|---|---|---|---|
| 782.7 | 783.5 | 783.5 | 783.5 | enter |
| 784.0 | 783.5 | 784.5 | new_profit changed |
|
| 784.6 | 783.5 | 784.5 | new_profit not changed: why? |
|
| 781.4 | 783.5 | 783.5 | ||
| 776.9 | 783.5 | 783.5 | exit |
What's wrong?
Solution 1:[1]
Finally, I came up with this solution:
entry = strategy.opentrades.entry_price(strategy.opentrades - 1)
profit = entry + tp
loss = entry - sl
extra = tp * .5
var float new_profit = na
var float old_profit = na
if not new_profit
new_profit := profit
if close > profit
if close > new_profit
old_profit := new_profit
new_profit := new_profit + extra
else if close < old_profit
strategy.close("long")
new_profit := na
old_profit := na
else if close < loss
strategy.close("long")
new_profit := na
old_profit := na
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tormec |
