The new-bar helper also needs a startup rule. With lastBar initially zero, the first tick after a restart counts as a new bar even if that candle began earlier. I would add one comparison case: restart midway through a candle with an existing position, then check that the closed-bar signal does not create a second entry. Decide explicitly whether startup may act on that old signal or must wait for the next bar.