re-wrote the logic.
Errors still might appear if you change timeframes frequently.
(you should not be seeing negative values, if you do then an error has occurred)
Based on how pine script operates with tick based data,
to avoid errors, it is advisable to:
• select your timeframe
• load the script
• adjust your settings
and leave it there for it to update.
If you need to change timeframes, it's advisable to repeat the steps.