The solution is described in the following page: https://help.mementodatabase.com/knowledge-base/using-memento-database-for-warehouse-inventory-management-a-beginners-guide/
In my setup, the initial quantity (or initial balance) is also stored as a normal transaction record. After that, all increases and decreases are handled simply as additional transaction records, and Memento Database’s lookup and aggregation features calculate the final total automatically. This approach works reliably without any scripts, since everything is handled by the standard functions.