Building a margin trading product in DeFi with $0 overheads


Intro

CEXes (Centralized Exchanges) have dominated spot/margin and derivatives trading volumes in crypto, close to $2.7T in volume in 2023.

 

I believe that over the next 2-3 years, there is a window of opportunity to grab market share from CEXes onto a DeFi application which provides a CEX-like experience along with self-custody.

 

CEXes cannot defend margins

  • CEXes have significant operational overheads due to liquidity requirements, maintaining lending power and maintaining infrastructure. This cost gets transferred to the user as trading fees.
  • Building on top of money markets like Aave and DEXes like Uniswap enables builders like us to tap into existing infra for liquidity & lending power which means trading fees for users can be considerably reduced.
 

CEXes cannot defend product

  • Protocols are now enabling cross-chain liquidity lending. Account Abstraction allows for web2-like wallet UX and overall tx throughput is consistently improving.
  • We are fast approaching a world where executing trades on DeFi can be as fast and seamless as CeFi.
 

To address this, I think CEXes will begin to build on top of decentralized protocols to have low-cost access to liquidity and lending power. They can reduce their dependance on market makers but maintain this option as a fallback in case liquidity and/or lending power dries up in DeFi.

Time to Experiment

My curiosity led me to build out a margin trading application on Polygon on top of Uniswap, Balancer and Aave and assess:

  • How are margin traders different from perpetuals traders?
  • How well can we compete on fees & is it a significant impact on traders’ earnings?
  • What margin traders think about the current UX and what it would take to switch out from CEXes?

The Product

  • Feature 1: USDC Margin Account Scrat creates a margin account for you by simply depositing USDC on Aave. It gives you 3 - 4.5x leverage backed by the Aave V3 protocol. Similar UX to any CEX.
    • notion image
 
  • Feature 2: Long & Short Positions Easily open longs & shorts on 5 assets. Understand how opening a trade affects your health factor & min. net position. Trade with leverage basis how risky the asset it. I specifically added stMATIC (3x leverage) which turned out to be the most used by a large margin
    • notion image
 
  • Feature 3: Tracking Trades PnL of your longs & shorts as well as current interest rates.
    • notion image
 
  • Feature 4: Portfolio tracking Track overall net position, P/L, health factor and minimum net position you need to maintain to avoid liquidation
    • notion image
 
  • Feature 5: Tracking Transactions Every single action you took including token prices at the time, timings and PnL.
    • notion image

How it Works

⚛️
Contract Code: CrossMarginTrading.sol | dApp Code: scrat-v1-interface

Stack

  • Nextjs, React, Supabase, Vercel
  • Solidity, Hardhat

Opening positions

  • Open long
    • On the UI, the trader is able to see the maximum position they are able to open. This is calculated as:
    • Then we send a request to the CrossMarginTrading.sol contract’s requestOpen(uint256 amount, address tokenAddress, uint8 direction) function which implements the following logic:
      • Initiates a flashloan of the entire position amount from Balancer in USDC
      • Swap USDC to the selected asset on Uniswap
      • Supply asset to Aave
      • Borrow USDC against the supplied collateral on Aave
      • Repay the USDC flashloan to Balancer with borrowed amount
  • Open short
    • On the UI, the trader is able to see the maximum position they are able to open. This is calculated as:
    • Then we send a request to the CrossMarginTrading.sol contract’s requestOpen(uint256 amount, address tokenAddress, uint8 direction) function which implements the following logic:
      • Initiates a flashloan of the entire position amount from Balancer in the selected asset
      • Swap selected asset to USDC on Uniswap
      • Supply USDC to Aave
      • Borrow selected asset against the supplied collateral on Aave
      • Repay the selected asset flashloan to Balancer with borrowed amount

Closing Positions

  • On the UI, the trader is able to see the P/L of the trade. This is calculated as:
  • Then we send a request to the CrossMarginTrading.sol contract’s requestClose(uint256 repay, address tokenAddress, uint8 direction, uint256 profit) function which implements the following logic:
  • Close Long
    • Initiates a flashloan of the entire close amount from Balancer in selected asset
    • Swap selected asset to USDC on Uniswap
    • Supply selected asset to Aave
    • Withdraw collateral that was supplied on opening the position (selected asset)
    • Repay the selected asset flashloan to Balancer with withdrawn amount
    • Make note of profit if any
  • Close Short
    • Initiates a flashloan of the entire close amount from Balancer in USDC
    • Swap USDC → selected on Uniswap
    • Supply USDC to Aave
    • Withdraw collateral that was supplied on opening the position (USDC)
    • Repay the USDC flashloan to Balancer with withdrawn amount
    • Make note of profit if any

Calculations

When opening or closing a trade, we dynamically calculate the effect of that action on the Health Factor and the Minimum Net Position that the trader needs to maintain

 

New Liquidation Threshold

notion image
 

New Health Factor

notion image
 

New Min Net Position

notion image

User Insights

20+ CEX traders used the dApp and 5 of them built their own bots using the scrat-v1 contract. I spent time connecting with traders on Discord, Reddit and Twitter to understand the market deeper.

 
  • How are margin traders different from perpetuals traders?
    • Perp traders:

    • Usually do quick ins-and-outs on positions and make trades over hours and days.
    • Positions are expensive to keep open and so unless a huge rally is expected on the asset, interest paid on the position quickly eats into profits.
    • Speed of execution is very important.
    •  

      Margin traders:

    • Margin traders typically maintain positions over longer periods of time.
    • They use margin to accumulate their portfolio and are happy with 2-4x leverage to manage risk (unlike perp traders who can take upto 100x leverage)
    • Speed of execution is much less important
    •  
  • How well can we compete on fees & is it a significant impact on traders’ earnings?
    • Very well, as captured by this comparative analysis:

      notion image

      Using DeFi enables Scrat to reduce fees by 50%-75% whilst still maintaining a healthy margin and without any initial capital injection.

 
  • What do margin traders think about the scrat’s UX and what it would take to switch out from CEXes?
    • Speed of trade execution (30s) was mostly fine for margin traders. We are limited by the speed of the L1/L2 we build on top of but wasn’t much of a concern.
    • The UI functionally had everything they needed other than price charts (which can be built by indexing the underlying AMM in realtime) but they certainly prefer their CEX’s UI and familiarity.
    • They are fairly price sensitive and loved the value prop of significantly lower fees and borrow rates.
    • They’re afraid of hacks. The scrat-v1 contract doesn’t ever hold user funds and we just inherit the risks from the Aave contracts — but traders are still wary
    • They didn’t care too much about assets being self-custody.
    • There’s still a huge hesitation to bridge over to DeFi as a whole. This is because of a combination of: learning curve, UX, on/off ramps and general acceptance of the concept.

My Takeaways

Where we are now

  • I was able to provide traders a decent trading experience and significant cost savings as a solo dev and with $0 of overheads. I think this is insane!
  • Self-custody of assets doesn’t have PMF yet. In fact, traders are more wary due to hacks that happen ever so often.
  • Liquidity isn’t nearly enough to onboard multiple whales, so we’re restricted by the growth of LP money into AMMs and depositors into lending markets.
  • On/off-ramp to/from DeFi, UX, security and just getting over the mind-block of moving to DeFi (probably a bit of a cultural shift) needs to happen before a product like this can truly take off.

Where we’re headed

  • I’m convinced of my thesis that CEXes wouldn’t be able to defend margins and product against decentralized counterparts but they have the advantage to abstract out many of the cons of DeFi whilst benefiting from the cost advantage.
  • In 2-3 years I believe that CEXes will begin to build on top of DeFi protocols to build up their cost advantage. They can reduce their dependance on market makers but maintain this option as a fallback in case liquidity and/or lending power dries up in DeFi.
  • As DeFi evolves in the next 2-3 years, it would certainly open up space for smaller teams to compete with them and grab market share from CEXes. This could be done even by small bootstrapped teams high profitability.