# Risks Proposal
## 1. Open Interest in the UI
We need to show infromation about the current level of Open Interest in the UI. We suggest displaying this information here

## 2. Alex's Document
> Based on this paper https://docs.google.com/document/d/1IEnOItBEi_MyWEXTqTxpHBb6tFG-qBqDzjN4x2HkEOA/edit#
* Point 1. Done.
* Point 2. Done except sub-point c.
* Point 3. We suggest to set maximum leverage is equal to 100.
* Point 4. https://www.bitmex.com/app/riskLimits bitmex analog. Now in research. The following model is proposed. If a trader has $< 30000 contracts$ $Initial margin$ is calculated as usual. Then every $10.000 contracts$ new $IM'$ equals $IM' = IM + 0.05 IM = 1.05 IM$ and $MM' = MM + 0.025 MM = 1.025 MM$. Need to be clarified.
Important to note that this model works with the *average* values. Liquidity transforms to the Open Interest and vice versa. By the way, we don't need this procedure if we'll implement socializid liquidations.
* Point 5. Next chapter of this document.
* Point 6. Kiev side.
* Point 7. Next chapter. Important to note: if we refund funds from liquidations, we will not refund money for ADL. If we accumulate funds from liquidations, then it is possible to return something for ADL.
## 2.5. Position Limits
### Open interest position limit
Currently the following model has been implemented: Trader's maximum position cannot have more contracts than 5 (may be 10) percent of open interest. If trader exeeds their position limit they cannot place more orders, which will increase their position. This model, however, cannot currently be used as open interest is small (100000 - 200000) and volatile, making it hard for traders with number of contracts more than 5000 - 10000 to trade.
### Insurance fund position limit
The position limits depending on the insurance fund have some theoretical issues. There are generaly 2 ways of calculating these limits.
First, we limit the position margin. If the position margin is small that means that the leverage is big, and position is risky, however it can be increased with the number of contracts, making the position even more risky for the exchange if it is liquidated. That is the main contadiction, because the increase in quantity or leverage makes the position more risky for the exchange, while they affect the position margin differently.
Second we can limit the quantity depending on how much contracts the exchange can have if it buys contracts by the current price. The main flaw here is that SHORT traders have more privileges, because if the current price goes down, they not only win from the price difference, but they can increase their position, as the exchange can afford to buy more contracts with its IF.
Neither of those ways, therefore, will be implemented.
## 2.7. Licudations and ADL proposal
### New Licudations
We will use the following notation for **cotract** $i$: liquidation price $LP_i$, bankruptcy price $BP_i$ and margin $M_i$. To describe the model let us consider only LONG contracts which were liquidated, as it will be simmilar for SHORTs .
1. Contracts in the liquidation engine are grouped by their banckruptcy price and those groups are sorted from the highest price to the lowest. Let $LG_i$ be i-th of these groups and $n$ be their total number, therefore $\forall t, k \in LG_i, BP_t = BP_k$ and if $u \in LG_i, v \in LG_j, i<j$ then $BP_u > BP_v$. Engine will try to close contracts by groups in order described above, however inside one group closing will be random.
2. If contract's $BP<SP$ or $BP < BestBid$ the liquidation engine closes it by the best bid. In the first case the exchange suffers some losses, but the risk of such contract to be closed for even worse price is lower. If $BestBid \leq BP \leq SP$ contract will not be closed and will stay in the liquidation engine for the next round.
3. For group $i$ we culculate $GPnL_i$ (group PnL) which equals to $\sum\limits_{t \in LG_i} (ClosingPrice - BP_t)$. If contract cannot be closed (see point 2) it is removed from the group untill the next round.
4. We culculate TPnL (total PnL) which equals to $\sum\limits_{i = 1}^{n} GPnL_i$. If $TPnL \leq 0$ no money is returned to traders. If $TPnL > 0$ there are groups with positive $GPnL$. In total traders in i-th group with positive $GPnL$ will get back $TRV_i$ (total return value):
$$
TRV_i = \frac{GPnL_i}{\sum\limits_{i = 1}^{n}\max\left(GPnL_i, 0\right)} TPnL
$$
The idea is that each group with positive $GPnL$ desrves the same part of total profit, as if there were no losses, while traders in groups with $GPnL \leq 0$ deserve nothing.
5. If the group's $GPnL > 0$, traders, whose contracts are in this group will be returned the equal share of their contracts' margins. For exemple, for contract j trader will be returned $RV_j$ (return value):
$$
RV_j = \frac{TRV_i}{\sum\limits_{t \in LG_i} M_t}M_j
$$
### Risks and ADL
We will devide the state of the exchange in 5 categories:
1. There are no liquidated contracts. It is the perfect scenario and everithing goes smoothly.
2. There are liquidated contracts and all of them are closed with profit. In that case all this profit is returned to traders as described in the previous part.
3. There are contracts which can only be closed with losses but we have enough insurance fund to handle that. This situation is also described in previous part.
4. There are contracts which can only be closed with losses but we do not have enough insurance fund to handle that.
4.5. If necessary, contracts are closed forcefully. Order in which contracts are closed depends on their rating $r = PnL* (1 - \frac{1}{leverage})$. The higher the rating, the earlier this contract will be closed. We can also create a BitMex analogy and devide contracts by groups. Contracts in one group will be closed randomly.
5. The insurance fund is too small to compensate the losses and we have to stop the exchange.
There are issues with each of the states except for the first one. For the 2nd the major issue is that while closing, for example, liquidated LONG contracts we are lowering the best bid, therefore artificially creating difference between spot and the last trading price. The general idea is to use some condition to control how much contracts we close during one liquidation round. There are several proposals:
* a. We limit the difference between LTP before closing the liqudated contracts and the current one. So when this difference is reached we stop closing the liquidated contracts.
* b. Same as the previous one, but we use the difference between current LTP and spot price before the closing.
* c. We calculate the difference depending on how many liquidated contracts we have (for example lineary). It can be appplied both to the 1st and the 2nd case.
Same goes for the 3rd state, however now we also have to find the difference between the 3rd and the 4th state. The main idea is to define what is a "small insurance fund". Once again there are several proposals:
* a. The losses from current unclosed liquidated contracts are higher than some percentage of the insurance fund.
* b. Insuranse fund is smaller than some value that is constant or depends on the OI (for example lineary).
If the exchange reached the 4th state no liquidations returns are paid. Also if the trader closes their position and has the profit it is devided by the trader's leverage. The idea is that they recive the profit if their leverage was 1 to begin with and, therefore, they had less contractes to obtain with the same margin (deleveraging). The rest of the profit goes to the exchange.
$$ RecievedPnL = \frac{1}{leverage}PnL $$
To describe the 5th state we once again need to create certain conditions. Here can be applied conditions mentioned earlier for state 4 with different parameters to complement the already existing one (look Exchange auto-stop)
## 3. Order Margin
This point about new procedure of calculation $Order Margin$. Adam has a idea that if a trader has an active position margin, the opposite order margin to the open position should not be. But what to do if the trader has an open position and place new orders (margin for which is not whitdrawn), suddenly the position os liquidated, and the orders are matched. A situation of negative balance and negative margin coverage is possible.
### Calculating of trader order margin for one market
Trader Order Margin - is the funds from trader's balance that will be blocked when trader placing an order.
Below, it is assumed that the order has quantity = 1. That is, if a trader has an order with quantity = n, then below we will assume that these are n orders with quantity = 1.
$OB$ - Order Book
$OB_{i,m}$ - Orders of trader $i$ (all of their orders in a _State_) on market m
$OB_{i,m}^S$ - Sell orders of trader $i$ on market m
$OB_{i,m}^B$ - Buy orders of trader $i$ on market m
$OB_{i,m} = OB_{i,m}^S \cup OB_{i,m}^B$ and $OB_m = \cup_i OB_{i,m}$
$OB_{i,m}$ is ordered (by price and precedence)
$P_{i,m}$ - Position of trader $i$ on market m
$PQ_{i,m}$ - Position Quantity on market m
$PM_{i,m}$ - Position Margin of trader $i$ on market m
The margin of $PQ_{i,m}$ orders, opposite to the position that will be executed first, should not be taken into Trader Order Margin, because of it covered by position.
**If trader has a Long position** Trader Order Margin is calculated for sell orders that are not covered by the position and all buy orders:
$\widehat{OB_{i,m}^S}$ = $OB_{i,m}^S$ without first $PQ_{i,m}$ orders
$\widehat{OB_{i,m}^B}$ = $OB_{i,m}^B$
**If trader has a Short position** Trader Order Margin is calculated for buy orders that are not covered by the position and all sell orders:
$\widehat{OB_{i,m}^B}$ = $OB_{i,m}^B$ without first $PQ_{i,m}$ orders
$\widehat{OB_{i,m}^S}$ = $OB_{i,m}^S$
So **Trader Order Margin** can be calculated as:
$OM_{i,m} = \sum_{ord\in \widehat{OB_{i,m}}}^n OM_{ord}$
$\widehat{OB_{i,m}}$ = $\widehat{OB_{i,m}^S}$$\cup \widehat{OB_{i,m}^B}$
**Trader's Locked Balance on market m** can be calculated as sum of a margins:
$LOC_{i,m} = OM_{i,m} +PM_{i,m}$
## 4. Privileged API
There are two opportunities for increasing of liquidity.
* Priveleged API is allowed some traders to take liquidated contracts at the $Bankruptcy price$.
* First Look at the order book. Set new orders ahead.
## 5. Maximum Leverage
To calculate the maximum leverage lets create the model which describes the worst case scenario. First we will describe the situation for LONG traders. Suppose traders place orders to buy OI (as it will soon become an open interst) contracts to open their LONG positions at the highest price HM (high mark) during some period with max possible leverage (ML). Then, that exact amount of contracts is matched with the orders on the opposing side. Price goes down and these contracts are liquidated. However, the remaining BUY orders are placed only at the lowest price during the same period (LM). The exchange does not want to lose more than x * IF, where IF is the insurance fund and x is the maximum share of it we are willing to lose. Therefore we can write the following:
$$OI * (BP - LM) \leq x * IF,\quad \text{where} \quad BP = HM - \frac{HM}{ ML}$$
we can rewrite this as
$$HM / ML >= HM - LM - \frac{x*IF}{OI}$$
if the right part is $\leq 0$, there are no restrictions non max leverage, otherwise:
$$ ML <= \frac{HM}{HM - LM - \frac{x*IF}{OI}}$$
The expression in the right part is always greater than 1, as denuminator is always less than the numerator.
For SHORTS the model is mostly the same, but the contracts in the begining are selled at LM and the price then goes up. So the condition will be
$$OI * (HM - BP) <= x * IF, \quad BP = LM + \frac{LM}{ML}$$
Once again if $HM - LM - \frac{x*IF}{OI} \leq 0$ there are no restrictions, otherwice:
$$ML <= \frac{LM}{HM - LM - \frac{x*IF}{OI}}$$
which is less than that with LONG ones. Also theoraticly it can be less than 1, for example, if $HM > 2 * LM + \frac{x*IF}{OI}$.
The culculations for the btc prices for 1 week, 1 month and 6 month can be seen in the following table:
https://docs.google.com/spreadsheets/d/1JsLvppXuzIQ52TwWXLPacxL3LxN6UTrWmuSQUYU6z5M/edit?usp=sharing}
The size of IF does not represent the real state, and is there only to show the model.
## 6. Available Balance for Multimarket
**Trader’s Available balance** can be calculated as:
$$ABAL_i = BAL_i - \sum_m{LOC_{i,m}}$$
If after some change of trader state on market m and $ABAL_{i}$ is not enough, some orders will be canceled on this market.
- suggestion: last orders in the OB queue are canceled first. As many as needed are canceled.
- suggestion: all orders on the side, opposite to the position or on both side if a trader has a zero position
## 7. ADL and liquidations refunds
The exchange can return money that traders lost due to ADL to them if the insurance fund is significant enough, for example, these refunds cost less then 5% of the IF. Trader's losses realted to the ADL can be easily calculated with the ADL algorithm introduced above (and below). However, if the exchange returns money from the liquidations to traders, the insurance fund cannot be increased without third party funding (concidering the regular situation with ADL turned off). Therefore, in this model money, that traders lost because of the ADL shuold not be returned, as the exchange then will lose everithing it recived from the ADL, living it in the same position as before the ADL was turned on.