I think it could probably be implemented more simply than that.
the implementation is not the problem, the problem is what's happening when the market goes against your positions and you get a margin call but your funds do not cover total loss
example, i know you can do the math but to let it clear if anyone have questions and I dont include fees and interest --you are long since 13.20 and you put your stop loss at 13usd
--I decide to dump and sell 30 000 bitcoins
--my order in mtgox is number N
--mtgox start to process my order
--the price gets at 13usd
--your stop loss is triggered
--your order in mtgox is N+23
--mtgox will process my order that the other 22 orders and then yours
--but you get processed at 12.50 and you got 50 cents slippage,(13 was the initial stop but u get out at 12.50) your account funds needs to cover the 70 cents loss per bitcoins if not bitfinex will lose money in case of a loss stock and forex brokers will call your home and tell you have 48h to pay the loss or get sued you can see that there is a big difference of condition from "real world" to bitcoin world
now lets look if we count total equity (wallet funds+gains) for leverage
--again your are long from 13.20 100 bitcoins based on your deposit of 20 btc
--at 13.50 you have gain 100x0.30=30 usd
--30x5=150, 150/13.50=11.11 so u can add 11 bitcoin to your long
--your positions get closed to same 12.50
--11x13.50= 148.5 11x12.5=137 148.5-137=11.5 loss
--100x13.20=1320 100x12.50=1250 1320-1250=70 loss
--total loss 70+11.5 = 81.5
---if you don't use equity for leverage your loss is just that 70
--total wallet value 20*12.50=250
--81.5/12.50=6.52 so bitfinex will take 6.52 BTC from your account in order to pay the user that lend you USD to go long (fees not included)
what happen if the market does not stop at 12.50 and it stops at 10USD and you position is closed at 10USD
Secondly, handle the insufficient margin problem in the same way you handle the 'no reserve' problem. So orders go into the open orders list and are fulfilled as much as the existing margin will allow. Remaining order stays in the open orders list but the status says 'no margin' and is not processed.
so if a user wants to go long 100 bitcoins but only get funds for 89 bitcoins, fill the 89 and ignore the remaining 11