Thanks for your reply.
Please refer this file.
Allocation of value in d4 should be on oldest to newest date basis.
I am using below formula, but it is not working when some values in column c are negative.
=MAX(0,MIN(C5,$D$4-SUMIF($B$5:$B$18,"<"&$B5,$C$5:$C$18)-SUMIF($B4:B$5,B5,$C4:C$5)))