HACKER Q&A
📣 max_

How Is Leverage Implemented?


I am thinking of implementing a a trading platform and wanted to implement the feature of leverage.

i.e someone having $100 but being able to trade with $1000 — the borrowing of $900 or 10x leverage.

How exactly does is this implemented in code, whats the mechanism like.

Is there a book where this stuff is described or is it just tribal knowledge?


  👤 quickthrowman Accepted Answer ✓
Implementing the code part of leverage is trivial if you understand what it is. Getting the risk management correct and following regulations is far more difficult.

Here’s how it works in a very simplified model (I assume BitMex works like this except they charge a borrow fee that I left out of my explanation)

Customer wants $1,000 of exposure to an asset by putting up $100 of margin at 10x leverage.

You lend $900 to the customer and with their $100, buy/sell $1,000 of the underlying.

Now you monitor their position. If the underlying moves against them by 10% and their margin deposit is gone, liquidate their position.

You would accomplish this by buying/selling the now $900 of the asset they bought/sold $1,000 of with leverage. If their liquidation caused you to receive less than the $900 you lent to them back, debit the difference from their account. If you receive more than $900 back, then you didn’t lose anything. Good job.

If they don’t liquidate by losing their margin and instead successfully close with a profit, they would get back their $100 + profit - fees, and you would get your $900 back, plus any fees/interest you charged for borrowing money.