Calculate Margin for Deals

Calculate Margin for Deals

I would like to ask if is there any way to calculate margin for Deals?

I have a custom füled in products "Buying Price".

In paper it is very easy to calculate:
=SUM for all Products ((Product Price-Buying Price) x Quantity)

But in practice i can not find a documentation that describes how can i make a custom topping / module to make this calculatiom and wite it back to the Deal's Custom Field: Margin.

Currently i do this manualay for every Deal, and i have 60-100 in every month.

I wonder if it can be automated.
I see that alot of small companies look only income for decision making, but margin is truly the next levél of view for every business.