to naderharb.m@
Not sure I understand where you get your time from when you write "2023-02-15 21:34:00.888854",? look to me like your machine time ?
would have been good to see also the Bar time supplied by IB in the print log of your run.
Sorry but still not sure I understand your issue.
Because the date of the bar is supplied with the Bar and uniquely identify the Bar (even with KeepUpToDate) from the experience I have with it.
This can be seen in the post from Jurgen, then just listen to bar_date. The trigger event to close your dict with previous one is when you get the xx:xx:00 bar, then assume your last xx:xx:55 is the correct last one for the last 5 sec. As Jurgen point it out, the math does work.
Avoid checking h=l=c which is an unsafe practice. I am even surprised that it works on instrument like TSLA (If you did it at 2100 EST then yes there is not that many transactions)
I do not assume that IB deliver an updated RT bar with every ticks.
Aside of calling for 1m bar, an alternative is to use Ticks.? (you are already dealing with 5 sec Bar with KeepUpToDate so pacing limitation start to be an issue anyway)
Ticks looks like arriving reasonably ordered with market, within the supplied time in second that mark them, so your not very wrong if you timestamp them using machine time truncated from each second.
With Ticks you can filter it doing whatever you want to build your bars set.
But somewhere it's back to same issue, you need to trust IB time marker (and it seems that they build it as it should)