Nice work on this algo, I like is that you consider whether the previous spread has reverted before estimating new parameters, sometimes new estimations cause a position to be closed before the original spread was profitable. Tracking the pair's pnl helps avoid that, but it's good to keep the original parameters around anyway.
The drift in the hedge ratio tends to be the killer in pairs trading In my experience, you could try adding a maximum time you'll wait for a reversion, or track how far the original parameters have deviated from updated ones and change them when the model has gone sufficiently out of whack. I added a simple max holding period as an example. I also switched it to use log prices since the returns of the spread are,
(log(A,t1) - log(A,t2)) + beta*(log(B, t2) - log(B, t1)).
It's heading in the right direction though, you'll just need risk stuff and some decent pairs.
Thanks for sharing,