The margin can become invalid due to your calculation method, f.i. when you get a negative square root.

Example:

Margin = OptimalF * Capital * sqrt(1 + ProfitClosed/Capital);

Margin becomes invalid when ProfitClosed is negative and exceeds the Capital. For fixing this, you could just prevent a square root below 1:

Margin = OptimalF * Capital * sqrt(1 + max(0,ProfitClosed)/Capital);