Some ideas for Marginly v2

Risks of leveraged trading and how Marginly addresses them

Risks of leveraged trading and how Marginly addresses them. Some ideas for Marginly v2.

Introduction

We designed the Marginly protocol with the idea that risk management is crucial to any borrowing activity. The risks associated with spot leveraged trading are as follows: 1. Counterparty risk - Smart contracts are hacked or fundamentally broken so users can no longer access their positions and funds.

2. Technical risk - Technical issues with the trading platform, wallet software, and internet connectivity can disrupt the execution of leveraged trades.

3. Market risk - the risk of the market price fluctuations of the traded asset. the risk of sudden price jumps due to the high volatility nature of crypto or because of some unforeseen (black swan) events.

4. Liquidity risk - the risk of insufficient asset amounts to perform an exchange in required volumes. May be as external and internal:

  • External: Trade slippage may be high on the AMM in high volatility market.

  • Internal: There might be no liquidity inside the Marginly pool to trade or withdraw.

5. Margin call risk: If a trade goes against a user’s position, they may be required to deposit additional funds (margin call) to cover potential losses. Failure to do so could lead to forced position liquidation. This risk is closely tied to both the market and the liquidity risk. We will cover this risk when we talk about Market and Liquidity risks. Let’s address each of the risks in greater detail and discuss mitigation strategies both current and potential for Marginly v2.

Counterparty risk

This risk is easy to explain yet hard to control. Users may lose their funds due to bugs and/or exploits found inside Marginly smart contracts. This risk reflects the human factor in the development and audit of smart contracts, where occasional errors might seep in through the tests during the development stage and through the audit process during the audit stage.

The best way to mitigate counterparty risk is to follow a strict process in developing and testing the smart contract logic and code. At Marginly we cover all of the smart contract methods with unit tests that must be passed before any functionality gets updated. We also run integrational scenarios that involve testnet deployment and trading emulation with testnet tokens and Uniswap v3 mock. Additionally, the audit must be performed by 3rd party professionals on close-to-live scenarios by deploying and playing with the smart contracts to blockchain testnets. The audit report has to be publicly available. Quantstamp will audit Marginly v1 contracts. Finally, when the Marginly protocol is live, there will be a dedicated Marginly token allocation for the bug bounty programs, so white hackers may do their business!

Technical risk

This risk entails everything that is related to the proper functioning of Marginly interfaces, Walletconnect provider, and the wallet you use to sign blockchain transactions. In case anything goes wrong with the abovementioned components due to software bugs or poor internet connection, you may temporarily lose access to your Marginly position and thus fail to act timely on your portfolio.

We run testnets and contests and allow people to participate and interact with the app so we can catch all the interface and connection errors and minimize their occurrence. Our QA team follows scenarios of common user flows and makes sure interfaces and wallet management run smoothly in different browsers and on different devices.

We have created more than 100 manual tests for regression testing with specialized testing software. We run these tests once a month to assess the overall app behavior. We also collect extensive user feedback from our Discord server and categorize it so we can prioritize our future work.

We are working on the desktop version of the app at the moment, yet we recommend using the mobile version as we envision the mobile-first app future. We observed stable behavior and smooth running of the Marginly web app on the following operational systems and several cell phone devices:

iOS: version 15.4 or higher. Safari or Chrome browser, walletconnect with Metamask wallet. Android: Android 11 or higher. Chrome or Firefox browser, walletconnect with Metamask wallet.

To mitigate the technical risk we recommend using the Marginly app only with a stable internet connection. Please don’t hesitate to report UX bugs so that the dev team can fix them in a timely manner. You can reach out to us in Marginly’s discord and twitter. We will additionally consider bug bounty programs to motivate people to find non-critical technical bugs that impede the normal functioning of the app.

Market risk

This is the one risk we can analyze extensively using several statistical methods at our disposal. Market risk is important in the context of leveraged trading because it is closely related to the maximum leverage a trader should take and to the concept of liquidation prices.

The higher the volatility of the underlying tradeable asset, the less likely the pool is to recover the full loan amount in the event of default. Marginly incorporates volatility into the interest rate calculation, so traders pay more for the risk when the market volatility is high. Marginly runs a risk dashboard to monitor volatility and possible risks on-chain.

Using the Marginly dashboard users can quickly assess the current market regime and define their drawdown tolerance given the historical volatility distribution and simulated returns histogram.

Let’s consider an example: I want to long ETH and would love to know the safe level of leverage I can take. Here’s the approximate algorithm I would use with the Marginly risk dashboard: 1. Assess current and historical volatility measures:

This chart tells me that currently, the volatility is at the low range of the spectrum, which is confirmed further by the volatility cone chart: The median daily volatility is around 4% while right now we sit below 2.5%, so it's reasonable to assume a volatility increase in the near future.

2. Look at the simulated returns histogram. When simulating returns we assume that the underlying asset (ETH in our example) follows a geometric Brownian motion process intervened with Poisson-distributed price jumps. The threshold for classification of the price return as a jump was set at a magnitude of 10%. This parameter itself has to be reassessed periodically, as looking at the log returns chart for the past year we barely see returns exceeding 10% in magnitude, the 5% threshold (green lines) looks much better in the mid-term market perspective:

The histogram of simulated returns shows us the distribution of worst 1% daily ETH returns in 1000 simulations of random price walks. On average in 1% worst-case scenarios I can expect to see a price drop of the underlying asset (ETH) around 7% a day.

3. Calculate maximum tolerable leverage. Armed with the knowledge about worst 1% drawdowns, I now can gauge the expected asset move given its current price, volatility, and time period I’m considering for a leveraged trade:

So for example, given the ETH price around ~1700 USDC as of writing, the 7% average wost 1% drawdown, and 5 days trade period, I can expect ETH to move: 266 USDC or 15% in either direction. This number can be used to further calculate the maximum allowable leverage: Even if my ETH collateral in the worst case scenario falls by 15% over the course of 5 days, I still want it to cover my debt sufficiently enough to have room for a critical margin of 5% (max leverage = 20). So in total, I should bear a 20% drawdown at minimum. That means the maximum leverage I should consider is: Lmax=120% = 5

Currently in Marginly, there are two parameters which are used to control the Market risk:

  • Maximum leverage: the maximum leverage of any single position is allowed to have before it gets liquidated. This is analogous to the Liquidation threshold in Aave, for example. 80% liquidation threshold is the same as max leverage of 5 = 1 / (1 - 80%).

  • Interest rate: this parameter is scaled by leverage, in particular, the interest rate is proportional to the overall long or short leverage and the current volatility level of the underlying:

The higher the corresponding leverage and the higher is the underlying volatility the higher interest rate will be recorded for the corresponding party (longs or shorts). There is a nice market-driven touch to this dynamic. Interest rates adjust with the market and with the open interest in Marginly. If there are only longs in the pool, the interest rate for USDC lenders who provide USDC for borrowers to go long will be very high, potentially attracting more USDC lenders. If, on the other hand, shorts dominate the pool, the interest rate for ETH will be high and all ETH lenders will enjoy high interest, potentially attracting new ETH liquidity into the pool.

Current Marginly architecture:

Users get liquidated unconditionally when their portfolio reaches the maximum leverage level. The borrower effectively loses 5% of his collateral. This collateral is earned by the pool if liquidation happens automatically due to the riskiest position being liquidated every time the Marginly smart contract is invoked. Additionally, the liquidating position may be absorbed by any other position inside Marginly. We offer keeper service bots for this purpose. These are web3js scrips which when run constantly monitor the Marginly contracts in search of the arbitrage opportunities. Given that receiving position parameters are within the required margins after the absorption happens the entire collateral margin of 5% is earned by a single position.

Architecture considerations for Marginly v2:

  1. Some protocols, like Euler finance, for example, don’t liquidate entire positions and instead allow liquidators to return position health factor (leverage in our case) to the target level. Marginly could also target a long-term “sustainable” (see market risk sections to understand how to gauge sustainability) leverage. The pool could slowly deleverage user positions proportional to their debts to bring pool leverage back to the target.

  2. Another approach we consider is to allow trading/swapping inside the pool. crvUSD algorithm introduces an AMM that allows for dynamic arbitrage opportunities since the price of collateral inside the pool changes faster than the oracle price. Such a pool effectively sells low and buys high paying this spread fee as a cost of hedging its collateral. Marginly can incentivize arbitrageurs or liquidators to buy out collateral of positions with dynamic discounts when these positions approach critical leverage levels. This is similar to point one above and could come as a complimentary protocol feature.

  3. The third interesting option uses the fact that Uniswap v3 allows liquidity providers to concentrate liquidity in any arbitrary range. This feature allows LPs to model/mimic any liquidity distribution, including existing AMMs such as Curve, Balancer, or Uni v2. See this great Paradigm post for details. Ultimately, the Uniswap v3 LP behaves as a short cash-secured put or a covered call depending on whether the deployed liquidity is above or below the current spot price. Curious minds may follow this excellent explanation for some insights.

Consider the example: Marginly ETH/USDC pool sits on an ETH net long position, this means there is a risk of ETH price depreciation: if the ETH price drops to a certain strike price X, the long position will require liquidation. Liquidation means selling ETH on the market to recover borrowed USDC to wind down the long positions. There needs to be a guaranteed buyer to absorb this selling. Buying ETH at a predetermined price in a predetermined quantity is exactly how Uniswap v3 position behaves when USDC is deployed at the strike price that is lower than the current market price. So effectively, we can use Uniswap v3 LP positions as protection for longs! Same works for shorts by the way.

The idea sounds simple on paper but starts to get complicated when you start thinking about the actual protocol architecture. Do we implement our own concentrated liquidity AMM and use its liquidity as a hedge? Alternatively, do we allow Uniswap v3 LPs to lock their NFTs? How do we guarantee that locked liquidity will be used explicitly by the Marginly pools?

Liquidity risk

This one is relatively simple to understand. Let’s first understand the external liquidity risk.

The less liquidity there is on external trading venues, the smaller the chance that traders can make good execution trades. The lower the liquidity depth in the ETH/USDC uniswap pool, the less likely the Marginly pool is to recover the full loan amount in the event of default. Consider the following liquidity distribution as an example: this is the ETH-USDC Uniswap v3 pool liquidity distribution on Arbitrum. Different shades of blue show 2% and 5% spreads for reference. Around 10K USDC worth of ETH must be traded to move the price by 2%, and around 20K USDC is needed to move the price by 5%.

Now imagine that the protocol needs to liquidate the position which is 50K in size. This would move the pool price significantly more than the 5% (max leverage = 20) liquidation threshold. This is a good illustration of the external liquidity risk. Bear in mind that this risk is exacerbated when the market is in turmoil as LP providers start leaving the Uniswap pool.

Now let us consider the internal liquidity risk. We’ve covered one possible scenario in detail in our docs on Marginly deleveraging mechanics. Basically, liquidity may be absent in the pool when the protocol needs to liquidate an underwater position. Consider the following pool state as an example:

There are 3 users in the ETH/USDC pool.

  • Lender (0) supplied 20K USDC in liquidity.

  • Buyer (1) borrowed 18K USDC to buy 18 ETH using 1 ETH as collateral.

  • Seller (2) borrowed 12 ETH to sell for 12K USDC using 2K USDC as collateral. liquidated the pool will be in liquidity deadlock: the system needs 19 ETH for liquidation, but the pool has only 7 ETH left after the short seller sold ETH from the pool. The long position gets liquidated when the ETH price is falling, while the short position is net positive. The obvious solution here is to cancel out the fraction of the long position against the entire short position. Limiting the short position’s profit potential while at the same time curbing the long position’s loss.

  1. Position slippage: the maximum slippage allowed when opening or closing leveraged positions on the external AMM. The default value is 2%. The transaction will revert if trade results in higher slippage.

  2. Margin call slippage: the maximum slippage allowed when liquidating a position on the external AMM. The default value is 5%. The transaction will revert if liquidation results in higher than the default slippage.

  3. Base asset limit: Maximum allowable balance of the base asset in the pool. (ETH for example). This parameter is used to gauge the concentration risk of any given asset. Too much of an asset in the pool may lead to overexposure and an inability to handle cascading liquidations in market turmoil.

  4. Quote asset limit: Maximum allowable balance of the quote asset in the pool. (USDC for example). This parameter is used to gauge the concentration risk of any given asset. Too much of an asset in the pool may lead to overexposure and an inability to handle cascading liquidations in market turmoil.

Current Marginly architecture:

CurrentlyMarginly liquidates risky positions and sells their collateral on the corresponding DEX or AMM. In addition to covering the insolvent position on the open market, Marginly allows any willing party to absorb the liquidating position and realize its net value (we discussed this above).

There are also deleveraging mechanics that come into play when a borrower needs to get liquidated but there isn’t enough liquidity in the pool to sell his collateral. ETH collateral of long buyers pays off the ETH debt of short sellers, while USDC debt from long buyers reduces the USDC collateral of short sellers.

Architecture considerations for Marginly v2:

We want to address both the internal and external liquidity risks. Intuitively, the best way to address both of them is to amend or modify the deleveraging functionality in such a way that we resort to external AMM trading only in rare cases when there is no deleveraging option left on the table. This way the protocol won’t be doing trades on a thin market when liquidations need to happen, while at the same time solving for the internal liquidity risk, as the absence of liquidity inside the Marginly pool will not lead to deadlocks and will simply require the overall leverage to wind down within the pool.

The devil is, as usual, in the details. The concept of deleveraging is closely related to the idea of targeting a “sustainable” pool leverage as we discussed above in the market risk section. There are a lot of questions to be answered, just to give the reader food for thought here are some of them:

  1. Will users agree to the fact that their winning positions will get deleveraged automatically once liquidations of opposite side positions happen in the Marginly protocol?

  2. Should the protocol target some default (e.g. 50%/50%) pool asset value ratio to avoid the liquidity imbalance which may lead to the need for deleveraging?

  3. Should the protocol have a reserve ratio to disallow borrowing of all of the assets from the pool?

Conclusion

In this article we have covered some of the common risks related to leveraged trading and described how Marginly addresses them. We’ve also presented current issues, challenges, and open questions we face. We have presented some ideas for future versions of the Marginly protocol. We highly anticipate positive user feedback and discussion around these ideas. In the next articles, we will expand on the ideas presented here and will consider each proposed approach, and its pros and cons in greater detail.

Last updated