Margin Calculation issue.

I have created one application for education purpose. Its a virtual trading app.
Got one issue with respect to calculation in one case.

Step 1: Qty: 50 SELL. Margin Value is deducted from Balance.
Step 2: Qty: 50 BUY. Margin value is credited back to main account.
Everything works fine. Balance amount is updated correctly with profit & Loss.
Step 3: Qty: 50 Sell of same symbol. Margin Value is deducted from Balance.
Step 4: Qty: 50 Buy of same symbol.
Now, I am taking avg of two margin value and multiplying with balance qty i.e. then adding back to main symbol. It is creating issue.

Can any one suggest how these margin value is adjusted and calculated?

Margin is always on a portfolio bro, when you add extra position to hedge, you break the hedge for which you have to maintain more margin. Then after you take one more leg (step 4), margin reduces.