PerpX Whitepaper
Background
Introduction
Automated Market Makers or AMM first appeared during the famous Defi wave and brought in crypto a way to determine a price for the exchange of two assets (in this case of two cryptos), using a function bounding the product of the liquidity of the two assets to a constant: . Through the deployment of trustless smart contract on Ethereum implementing the above function, is was possible to automate the process of market making by using liquidity providers.
In this white paper, we introduce the concept of virtual Automated Market Maker (VAMM) and describe how this idea is leveraged in order to provide a trading platform for derivatives traders on the Starknet ecosystem.
Virtual Automated Market Maker
In a VAMM, the trader does not exchange real tokens but rather will take part in the trading of derivatives, for example perpetual contracts. The perpetual contract allows the trader to take a long or short position on a mark price, which will depend on the crypto asset’s index price which is usually corrected by a fee (e.g. funding rate).
The contract pays the differential between the underlying at the opening of the contract and the underlying at the closing of the contract. In most cases, the underlying is the spot price of a pair of assets, such as BTC/USDT.
It is important to note that no real assets are stored on the VAMM. Traders are able to make leveraged trades based on a collateral stored on a vault type smart contract.
Starknet
The reason why we decided to develop our exchange on Starknet is because it offers certain advantages compared to monolithic blockchains, even the fast ones e.g Solana.
- Scalability:
- Batch Transactions: Since transactions are verified in one batch, the marginal cost of verifying these transactions on Ethereum decreases as the number of transactions increases. On monolithic blockchains, the marginal cost of each transaction increases as the number of transactions increases.
- Hardware Requirements: It’s also easier to scale the hardware of the handful of nodes needed on a zk-rollup than to scale the thousands of nodes needed on a monolithic blockchain.
- Fractal Scaling: With Starknet it’s possible to run app-specific layer 3’s that settle on Starknet, which then settle on Ethereum. This allows to create extremely cheap app-specific networks, that still keep the security of Ethereum. It’s also possible to customize the architecture (such as storage structure) of these app-specific L3’s in order to avoid the scalability drawbacks of general purpose layers.
- Privacy: Using fractal scaling, you can also create a private layer 3 that settles on Starknet. For certain applications, privacy is a needed feature, e.g. traders who don’t want to disclose their positions on an decentralized exchange.
- Security: Starknet transactions are settled on Ethereum, which is the most decentralized blockchain, making it more secure and harder to shutdown than any other L1.
- Safe Exit: If Starknet goes down or if you want to leave the L2, you have the possibility to securely withdraw to Ethereum. If you are on Solana and it goes down, there is little you can do about it.
Arbitrum and Optimism share some of the same advantages as Starknet, but their main drawback is the fact that they rely on game theory for their security. The assumption is that malicious behavior will be detected at worst 7 days after the transaction. With Starknet there are no trust assumptions, zero knowledge proofs are leveraged in order to verify the correct execution of the code.
State of the Art
The below table aggregates the most well known VAMMs currently across multiple chains:
Pika | GMX | dYdX | Perp Protocol | |
Chain | Optimism | Arbitrum | StarkEx | Optimism |
Margin | (80% collateral + PnL + funding) > 0 | (collateral + PnL - borrow fee) > 1% of position size | margin > x% of position size | (collateral + PnL - borrow fee) > 6.25% of position size |
Isolated/Cross margin | Isolated | Isolated | Cross | Cross |
Liquidation | Partial | Partial | Total | Total |
Funding rate | dynamic based on open interests imbalance | dynamic borrow fee based on assets borrowed and available liquidity | dynamic based on index price, ask price and bid price | dynamic based on difference between mark price and index price |
Fees | 0.1% trading fee + 0.0003 ETH execution fee | 0.1% trading fee + 0.0003 ETH execution fee + price spread | varies with traders’ volume. Free below 100k$, goes up to 0.05% | 0.1% trading fee |
Liquidity providing | Vault locked USDC | Liquidity mining through GLP | Order book | Build on Uniswap V3 liquidity solution |
Leverage | ETH/BTC x50, rest x20 | x30 for all | BTC/ETH x50, rest 10x | x10 for all |
Collateral | USDC | USDC | USDC | USDC |
Margin
All the above VAMM use the below formula (or a modification of this formula) in order to calculate the margin requirements for a trader’s positions:
with , and the margin ratio, the size of the position and the index price at time of trade respectively. Out of the four mentioned VAMM, only dYdX uses a variable margin ratio which changes based on the traded asset.
Isolated/cross margin
While isolated margin allows for an easier implementation, cross margin allows a trader’s margin and realized PnL to be used across multiple positions. Pika and GMX have implemented isolated margin, while dYdX and Perp Protocol use cross margin.
Liquidation
Based on the type of margin that is used (isolated or cross), liquidation can happen in two of the following ways: partial liquidation, where each position is liquidated individually, or total liquidation, where all positions are liquidated.
Funding rate
Each of the above VAMM use a different method for the funding rate but all the methods can be generalized as a periodic payment to traders based on the current imbalance in the open interest. Perp protocol differentiates itself in the sense that it doesn’t implement a periodic payment, but rather settles the funding rate for a position when liquidity is added or removed, when a new position is opened or closed and during a liquidation.
Fees
All the VAMM have a trading fee implemented, which is based on a percentage of the trade’s size with some VAMM adding a twist, such as a fee reduction for token holders or an execution fee (allows for keeper bots to execute the limit and stop orders).
Liquidity providing
The solutions for providing liquidity ranges from simple solutions, such as Perp protocol building on top of the Uniswap V3 in order to allow liquidity providers (LP) to provide liquidity in a certain range; Pika which will simply lock liquidity into a vault type smart contract; or dYdX which uses an order book style implementation.
GMX uses a more complicated solution by giving liquidity providers a LP token, GLP, which tracks the index of assets available on the platform. The index for GLP will vary based on the positions of the traders. GLP holders are rewarded by earning some percentage of the platform’s fees.
Leverage
Leverage on all the studied platforms is fixed and based on the type of asset traded, with a leverage usually higher when trading BTC or ETH.
Collateral
For all the various VAMMs, the collateral must be provided by the traders in stablecoins, in this case USDC.
Summary
We can make some conclusions from the above characteristics we identified and studied:
- The implementation for margin calculation is an important step in the definition of the protocol, as it will decide how much leverage the traders can take, the risk of liquidation for the traders but also the exposed risk for the protocol.
- If possible, cross margin should be privileged over isolated margin, as it allows the protocol to be more capital efficient. On top of cross margining, PerpX also implements real time PnL realization, which means that at all times, the wins of a position will offset the loss of another.
- Protocols currently have implemented the funding rate as a periodic fee which is paid or received by the trader based on the imbalance in open interests. No other method has yet been implemented for the correction of the imbalance.
- VAMMs will take a fee based on the size of the position which is opened.
- Liquidity providing could easily be implemented in a simple but efficient way (e.g. vault type implementation à la Pika) and later on be improved through for example a LP token (e.g. GLP).
- All VAMM use a fixed maximum leverage which does not evolve based on market conditions.
In the rest of this white paper, we will use the above ideas for the implementation of our PerpX protocol and apply improvements where we believe improvements are needed.
Core ideas
The core component of PerpX is the aforementioned concept of VAMM. The VAMM will be used in order to set the price of each trade. The VAMM will calculate the sensitivity of the price for the trade, depending on how out of balance the positions of traders are, relative to the amount available in the liquidity pool.
The liquidity pool serves as a counter-party for all the out of balance positions the traders have taken. Say in aggregate the traders are net short, then the liquidity pool will be net long.
From the previous section’s summary and leveraging the computing power available on Starknet, we will be focusing on the following characteristics for our VAMM:
- On-chain dynamic margin requirements: we will be taking advantage Starknet’s capabilities in order to compute real-time transparent margin requirements from the asset’s volatility.
- On-chain dynamic leverage: maximum applicable leverage should depend on market conditions, ranging from in a very volatile market to in a calm market. We will be using Starknet’s cheap computation to calculate the maximum leverage on-chain for each asset in a trustless manner.
- Real-time PnL realization: fast oracle price updates will be send to the contract every second, which allows the contract to use the unrealized PnL in the calculation of the margin requirements.
- Cross margin: aiming for maximum capital efficiency, the protocol will be using cross margin.
- Imbalance fee: instead of the classic funding rate we have seen in previous VAMMs, PerpX will be using a novel method, consisting of an imbalance fee based on the imbalance in the open interests of an asset. The imbalance presents multiple advantages over the funding rate: more direct incentives to arbitrage for traders, direct traders punishment in case the opened position reinforces the imbalance and reward in case of correct market prediction (e.g. early long during positive imbalance does not incur funding).
- Volatility fee: PerpX will calculate a volatility fee as a percentage of the imbalance fee.
- Fixed fee: PerpX will charge a fixed percentage fee on the traded notional.
- Simple LP reward: LPs will be rewarded through the imbalance fee which will be split between the protocol and the LPs.
VAMM State
The state of the VAMM is composed of
- : Notional amount of longs
- : Notional amount of shorts
- : Notional amount of liquidity in the pool
- : Imbalance of the pool, defined as
Trading
In order to keep track of a trader position PnL, we introduce the cost variable, , which is the net cost paid to enter/leave the position. With being the net quantity of contract open and the oracle price, we have
This formula stays correct if the user closes their position, with . In that case, tracks the cumulative realized PnL of the user.
When the user trades, the price of the oracle and the imbalance of the pool are used to calculate the imbalance fee.
Trader Imbalance fee
The imbalance fee depends on the imbalance of the pool. The more the trade pushes the pool out of balance, aka the more increases, the higher the imbalance fee. If the trade brings closer to zero, the fee becomes a rebate, making an incentive for trader to push the imbalance back to 0. Formally, for an infinitely small size , the imbalance fee will be . As you can see, as reaches , the imbalance fee reaches the totality of the traded size , which makes it impossible for a trade to push the imbalance over one.
However, in practice, traders will not trade an infinitely small size. We thus have to derive a fee formula for an arbitrary size . To do so, we will split in parts of equivalent size, and we fix . We can approximate the fee to be paid with the following sum
Now, let’s take the limit for and we get
The sum method is intuitive, but we could also have derived the formula using the following integral .
As an example, let’s take a pool with the following state:
If a user decides to go long 10 contracts, and the fee will be . Which brings our user’s cost of trade to . Let’s use the formula above to calculate the user’s PnL: . We can see that the user won $5 simply by bringing the imbalance of the pool back to 0.
If a instead a user decides to go short 10 contracts, and the fee will be . Which brings our user’s cost of trade to . Let’s use the formula above to calculate the user’s PnL: . We can see that the user lost $15 by pushing the pool even more out of balance.
Let’s now show that a trade will never push the imbalance over 1. Let’s take a pool with the following state:
If instead a user decides to go short 10 contracts, and the fee will be . The state of the pool after the trade will then
be
The trader paid more than the entire cost of the trade as imbalance fee, which gets added to the liquidity pool and brings the pool imbalance to . We note that the change of price can increase the notional exposure of the open positions and lead to an imbalance higher than one.
LP Imbalance fee
The imbalance fees also apply to liquidity providers. Indeed, bringing liquidity or removing liquidity in the pool can effect its imbalance. This time however, the effect is on . We can take the same derivation as above, applying the change in liquidity to the denominator.
We can extract the below fee formula from the change in imbalance:
However, since the fee does not depend on the direction of the imbalance but rather the change of the imbalance, we need to take the absolute value of . Additionally, if , the provided liquidity reduces the imbalance and hence the LP should receive a rebate. Hence we need to add a negative sign to the above formula. We end up with the below value for the LP imbalance fee:
Let’s show how the change in liquidity affect the imbalance and what fee the liquidity provider will have to pay. Let’s take a pool with the following state:
This pool is highly biased short. If a liquidity provider decides to add $1000 of liquidity, we will have:
The LP provider receives a rebate of $623 since he reduces the imbalance of the pool by providing liquidity. Now let’s look at another example with the pool in the following state:
The pool is biased long. If a liquidity provider decides to remove $500, we will have:
The LP pays $623 fees in order to remove is liquidity since he increases the imbalance in the pool.
Volatility fees
As the imbalance fee is net zero in average (when the pool imbalance is back to zero, the total amount of fee received matches the total amount of fee paid), we still need to reward the liquidity providers for being exposed to the volatility of the underlying. We introduce another fee called the volatility fee. The volatility fee is calculated as a percentage of the imbalance fee. That way, if a pool goes out of balance often, it will have a higher yield. This higher yield will bring more liquidity to the pool, which will reduce how often the pool goes out of balance, and thus lower the yield. This self healing mechanism allows the market to figure out automatically the right amount of liquidity to allocate to an instrument depending on its volatility.
Fixed fees
In order to integrate a clash flow into our exchange, we collect a fixed percentage fee on each trade of 2bps. Those fees are then added to our treasury
Execution fees
This small fee will be perceived on limits and stop orders in order to pay keeper bots when executing the trade.
Trade batching
Each trade gets added into a queue after being posted, and settles only at the next oracle update. This is done to prevent the front running of the oracle. To prevent trades from happening too long after they were posted, an expiration parameter is added. If the timestamp of the oracle is after the expiration timestamp of the trade, the trade isn’t executed.
Oracles
In order to process batches of trade quickly, we need to have a “push” based fast oracle, instead of the traditional “pull” based oracle like Chainlink. PerpX will assure the service of oracles. In case of PerpX not being able to publish oracles anymore, no new trade will be executed due to the trade batching logic, which means that implicitly, all the positions will be settled at the last updated price. An escape hatch mechanism will allow users to withdraw their money as long as their net account equity is greater than zero.
Liquidations
The protocol doesn’t manage liquidations, instead, it is up to arbitrageurs bot to look for accounts that go under their maintenance margin, and trigger a global account liquidation. During an account liquidation, all the user’s positions are closed, and a percentage of the remaining margin is given to the arbitrageur bot as an incentive, the rest going to the liquidity pool as a liquidation fee. If after the liquidation, the net margin is negative, the loss will be reflected in the liquidity pool.
A liquidation is only valid if is less than the required margin ratio for the instrument.
Margin requirements
In order to manage risks, we enforce margin requirements on the traders’ positions. The margin requirement is based on the value at risk of the position, which depends on the position size and the instrument’s volatility. The value at risk () over an horizon and a confidence level can be expressed as , where denotes the quantile of the assumed distribution of returns, and the notional value of the position.
Using historical data for Ethereum over a span of 1 year, we aim to capture the needed parameters of the previous formula for our value at risk. The following methodology is used: the volatility for the asset is calculated with an exponential moving average with a half life of 10 hours, using the as our estimator for the variance. The volatility is multiplied by the quantile and the maximum between this value and a price variation is selected. Finally, we compare this with the 5 seconds future return in order to determine if the margin calculation will hold. The below formula expresses the exact inequality we are solving over the one year data:
Using this inequality, we can brute force the data (using a simple grid search for example) and extract the appropriate value for , the quantile for the distribution of the returns.
We need to use a half life for the exponential moving average on the data big enough so that the volatility doesn’t increase too fast and brings traders’ margin under the requirements, triggering a liquidation. However, we also want the half life to be small enough so that the volatility measure is reactive to market events.
Using a half life of 10 hours, and a of 42, the 5 seconds returns never crosses the margin requirement during the whole backtested period of one year (no liquidated position is underwater), as can be seen on Figure 1. The implied leverage oscillates between 100x (our maximum), and 50x, with minimums at 20x during periods of high volatility.
.png)
Arbitrage
The arbitrage between PerpX and other exchanges is quite explicit. Let’s take the following configuration. The imbalance is positive meaning shorts will receive a rebate. The trader opens a long on the spot market, and a short on PerpX.
They buy 10 contracts, , the fee will be . Which brings our user’s cost of trade to and profit . Now, the trader’s position is delta neutral, each win or loss of each one of the position will be compensated. However, if the trader exits its position, they might not capture the $5, as they will bring the imbalance of the pool back to its initial state. They therefore have to wait for the imbalance of the pool to decrease (wait for other traders to long) to realize the arbitrage and close their positions. Arbitragers will then have to model the mean reversion properties of the imbalance, in order to anticipate the time during which they will have to keep their position open, and they can close it without any cost, therefore when an equivalent amount of long has entered the pool. The profitability of the trade will then depend on the expected duration of having the position open, and on the cost of the hedge. The captured profit can be described as
where is the duration for which the position is kept open, is the risk free interest rate, and is the cost of the hedge. As you can see, the profitability of bringing an imbalance back to 0 depends directly on the speed of mean reversion of the pool and the cost + opportunity cost to hedge the position. We can actually derive the arbitrage free imbalance at equilibrium if and are known, for a given trade size , using the following
Tokenomics
The protocol will be releasing a token in order to attract volume on PerpX. Tokens will be distributed as a reward for early traders/LP.
In addition, generated fees from the protocol (Fixed fees) will be used in order to buy back the PerpX tokens on a Starknet DEX, which will be burned. This way, value from the protocol can be transferred to the token holders. In order to add an extra incentive in keeping the imbalance of the pools around 0, the buy and burn mechanism will only trigger when the imbalance of the pools are under a certain threshold, otherwise the protocol will keep accumulating a treasury in USD. This will allow the protocol to only burn the token when the LPs aren’t over exposed and potentially keep the fixed fees as a security fund.
Backtesting
In order to backtest the performance of the liquidity pool, we use the price feed of different assets, and simulate trader’s trades with normally distributed random numbers. We plot graphs for the liquidity pool size, the traders’ aggregated net position, traders’ PnL and the liquidity pool imbalance on Figure 2, Figure 3, Figure 4 and Figure 5 respectively. In order to avoid unrealistic scenarios where the traders would constantly long/short into a pool which already as a strong short/long imbalance, we add a mean reversion parameter on the trade size. This means that if we sample a long, and the pool imbalance is already strongly short, we reduce the size of the trade, same for shorts.
for q.next():
ts, trade, _ = q.read()
# Cannot use trade size as it is not centered around zero
size = rand.normal(0, np.abs(trade.size()))
if size < 0:
size *= 0.2 * ((ex.imbalance())) + 1.
else:
size /= 0.2 * ((ex.imbalance())) + 1.
ex.trade(size)
if ts - lastTs > 1s:
lastTs = ts
# Oracle update every 1s
ex.update_price(trade.price())
In our first backtest, we use the price feed for Ethereum on Coinbasepro, over five days, between Thu Apr 15 2021 15:20:00 GMT and Wed Apr 21 2021 10:13:20 GMT. Over that period, we see a volume of ~$16 000 000 000. We fix the volatility fee to 1%, and the pool liquidity to $1 000 000.
We can see that the liquidity pool is obviously very profitable, with an annualized Sharpe ratio of 13. The profitability of the pool is linked to the low amount of liquidity compared to the traded volume. In that environment, the high yield should attract more liquidity providers and reduce the volatility of the pool, but at the same time reducing its yield. Let’s re-run the same numbers but with a pool with a bigger amount of liquidity, $100 000 000.
We can see that the volatility is reduced, and the yield too, resulting in an annualized Sharpe ratio of 6. The reduced Sharpe ratio is due to the increased pool liquidity, which lowers the magnitude of the imbalance and therefore the total amount of volatility fees. Of course the Sharpe ratio here is unrealistic, and it implies that the fees are too high for the amount of volume traded, or the provided liquidity is too low. In reality, we should see a Sharpe ratio similar to other liquidity provision strategies, which implies that the volume traded will scale down when the volatility fees increase.
Overall, there is no point in trying to calculate an optimal volatility fee, as it can be seen as a parameter that will influence the amount of trading volume on the platform. Indeed, the Sharpe ratio on the liquidity provision will stay the same, whatever the volatility fee is set at. We therefore decide to use a fee of . This value is based on our back testing, which showed that the imbalance of the pool would oscilates between and . Using a volatility fee of allows the protocol to generate, during the worst imbalance state of , a trading fee equivalent to the current VAMMs of .
We remind our readers that this doesn’t mean the user will pay of its trade notional as fee, but of the absolute value of the imbalance fee as fee. This means that in an optimal scenario where all traders match with each other and the aggregate net position is 0, the fees are of 0. This is expected behaviour as the liquidity providers are not taking any risk, because the wins of each trader is covered by the loss of others, and not by the liquidity pool.
Pika V2
We analyze the behaviour of the Pika V2 protocol, and compare its performances with our model. We start with replaying the trades for ETH/USD, with no imbalance fees. At its maximum, the Pika V2 vault had $35 000 000, used as liquidity for 10 instruments. We will thus assume a liquidity pool of $5 000 000 for ETH/USD only, as our exchange has a liquidity pool per instrument, unlike pika.
We see on Figure 10 and Figure 13 that, even though the liquidity pool made a profit, it took a grotesque amount of risk by allowing the imbalance to climb all the way to 4. This meant that the pool was exposed to $40 000 000 dollars of notional short on ETH/USD, which makes it very clear why the protocol was shut down, as there wasn’t any mechanism strong enough to bring that imbalance back to 0.
We compare the results with our implementation of the imbalance fee mechanism, and look at the behaviour of the pool in blue on Figure 10 to Figure 13.
We can see that the performance of the liquidity pool is a lot better, due to the imbalance fees that were paid by the traders for exposing the liquidity providers to a big amount of risk. The imbalance was limited to 1.2, and the liquidity pool had a return of 600%.
Our implementation will force the traders to reduce the imbalance of the pool and would have never allowed an imbalance of 8 to be reached, due to the mechanism of imbalance fees PerpX uses.
Summary
It is clear from the backtests that our adaptive fee mechanism is more appropriate for a VAMM. Indeed, unlike other VAMMs, we actually take into account how much the liquidity providers are exposed to market volatility, and use that to incentive re-balancing towards 0. The sharpe ratio for the pool is beyond or on par with the risk/reward ratios we experience in crypto, making it an attractive option to provide liquidity into. Also, the modularity and generalization power of our fee model allows us to integrate more complex instruments in the future, such as options.
When it comes to the user experience, traders will be able to enter and exit positions easily. Thanks to the speed of the starknet network, our always available liquidity, and our adaptive margin requirement, they will only be liquidated at the last second, only when it is ultimately necessary.