'Ta.valuewhen used in conjunction with strategy.position_size

I'm currently trying to craft Pine Script code that allows for a position to be closed after a certain number of bars and have run into some difficulty. Here is the relevant section of my code:

//Time in trade

lasttradeindex=ta.valuewhen(strategy.position_size!=0,bar_index,0)

timeintrade=0

if strategy.position_size!=0
    timeintrade:= bar_index-lasttradeindex

The lasttradeindex variable determines the bar index when the last opening trade was executed, whether it is involves opening a long position or a short position.

What I am puzzled about is why when I plot the variable timeintrade, the value of the variable does not change (remains at 0) even when the code clearly contains a stipulation for the value of timeintrade to change to bar_index-lasttradeindex when the strategy position size is not equal to 0 i.e when there is an open position.

Any advice that points me in the right direction would be appreciated.

Thanks.



Solution 1:[1]

Using v5 built-ins you can access trade entry times as well as their ID's. @adolgov on TV has a great example here using this function to check time against trade entry times and close trades outside of the window:

closePositionAfter(timeoutS)=>
    if strategy.opentrades > 0
        for i = 0 to strategy.opentrades-1
            if time - strategy.opentrades.entry_time(i) >= timeoutS*1000
                entry = strategy.opentrades.entry_id(i)
                strategy.close(entry, comment = str.format("Close \"{0}\" by timeout {1}s", entry, timeoutS))

Cheers and all the best

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 Bjorgum