I've created a strategy that buys and sells based on an indicator. After buying it will follow te SAR for stop-loss. the strategy is set to execute every tick.
This parts works fine.
I have however one more condition and that is that I close half the position when certain conditions are met. However, the strategy keeps closing half the remaining position every tick, until the complete position is closed.
I've tried to use the position_size variable to check the remaining position against the initial position and also introduced a bool variable to indicate that trimming has been taken place, but it is not working.
What can I do to stop the strategy from completely closing the position?
strategy("MyStrategy", overlay=true, calc_on_every_tick=true,
commission_type=strategy.commission.percent, commission_value=0.075, slippage=2)
...
bool trim = na
if TDUp == 9 and not trim and high > strategy.position_avg_price and strategy.opentrades >=
strategy.opentrades[max(0, barssince(Buy)-1)]
// this shall execute only once, but it is executed every tick
strategy.order("triml", false, qty=abs(strategy.position_size / 2))
trim = true
if TDDn == 9 and not trim and low < strategy.position_avg_price and strategy.opentrades <=
strategy.opentrades[max(0, barssince(Sell)-1)]
// this shall execute only once, but it is executed every tick
strategy.order("trims", true, qty=abs(strategy.position_size / 2))
trim = true