How to know if last trade closed was a long or short in strategy

Viewed 63

Can anyone tell me how to know if last trade closed was a long or short in strategy please.

Thank you.

2 Answers

There is a built-in variable for that that tells you what your open position is:
strategy.position_size

For closed trades first you need to find your trade (or trade ID). If it was the very last, it's as simple as that:
strategy.closedtrades.size(strategy.closedtrades - 1)

If the value is > 0, the market position was long. If the value is < 0, the market position was short.

Use the strategy.position_size built-in variable to figure out if a position is closed and its direction.

is_pos_closed = (strategy.position_size[1] != 0 and strategy.position_size == 0) or ((strategy.position_size[1] * strategy.position_size) < 0)
is_long = strategy.position_size > 0
is_short = strategy.position_size < 0

Then all you need to do is when a position is closed, check if the direction was long or short on the previous bar.

was_long = is_pos_closed and is_long[1]
was_short = is_pos_closed and is_short[1]
Related