How to accumulate Balance for Statement of Account in print format

Hi all,

I am in the midst of creating statement of account from print format.

{% set details = frappe.get_all(‘GL Entry’,
filters={
‘posting_date’:[‘between’,(doc.from_date,doc.to_date)],
‘party’:[‘=’,row.get_formatted(‘customer’, doc)],
‘docstatus’:[‘=’, 1],
‘is_cancelled’:[‘=’, 0],
‘cost_center’:[‘not like’, ‘%Main - HQ%’]},
fields=[‘*’], group_by=‘voucher_no’, order_by=‘posting_date, voucher_no asc’) %}

This is how I retrieve and filter the data inside print format which is from GL Entry.
My question is, how can I get the first balance from the first row and start calculate the sum of the balance ?

                    {% set firstbalance =  frappe.utils.fmt_money(detail.debit,currency="") %}
                    {% set balance = frappe.utils.fmt_money(detail.debit-detail.credit,currency="") %}
                   
                  
                    {% if loop.index == 1 %} {{ firstbalance }}
                    {% else %}  {{ balance }}  {% endif %}

I tried with those lines of codes but its not helping. Not be able to pass the 1st row value to the next one. How can I achieve this and where should I made the amendment ? Any help/guides is much appreciated. I’ve been stuck here almost few weeks already.

Thank you very much.