# Margin Trading - Concept Math Spec
[README](https://hackmd.io/@shrutiappiah/rkOnQeXZ_)
Margin trading occurs in the Liquidity Provider Subsystem. Each liquidity pool can choose whether or not it allows margin trading positions ($mtp$'s). Liquidity pools that offer $mtp$'s take on the added risk of $mtp$'s defaulting, which may lead to liquidity providers losing money. For this reason, $mtp$'s are considered a liability to the liquidity pool.
To buffer against the risk from $mtp$'s defaults, we present an insurance mechanism. Each liquidity pool that offers $mtp$'s able to collect $mtp$'s borrrow fees. In the event of a default, it is mandatory that the $mtp$ owner cover their position using their collateral. If they are unable to cover it, the liquidity available in the liquidity pool is used to cover the loss.
The borrow fee rates could be set via a governance process.
## State Space
### Global State ($X$)
The Global State describes all state variables in the margin trading module. For a given individual liquidity pool that holds an X:Y token pair, the margin trading module exists across each liquidity pool that offers this feature. In our initial examples, we describe margin long positions in which users are long asset Y. After we clearly define X:Y based margin longs, we go on to define X:Y -> Y:Z margin longs across two pools, as well as X:Y margin short positions in which users are short asset Y.
The global state can be segmented into Token States, Stateful Metrics, and Stateful Parameters.
### Token States ($\mathbf{T}$)
The primary set of state variables of the margin trading module are token pools.
| Name | Description | Symbol |
|----|----|----|
| X Assets | Total quantity of tokens of type X for a pool as an asset | $X_{A}$ |
| X Principal Liabilities | Total quantity of tokens of type X for a pool as principal liabilities | $X^P_{L}$ |
| X Custody | Total quantity of tokens of type X for a pool held in custody |$X_{C}$ |
| Y Assets | Total quantity of tokens of type Y for a pool as an asset| $Y_{A}$ |
| Y Principal Liabilities |Total quantity of tokens of type Y for a pool as principal liabilities | $Y^P_{L}$ |
| Y Interest Liabilities | Total quantity of tokens of type Y for a pool as interest liabilities | $Y^I_{L}$ |
| Y Custody | Total quantity of tokens of type Y for a pool held in custody |$Y_{C}$ |
To open a long mtp, users add tokens of type x to a pool as collateral, borrow additional tokens of type x, and then swap their x tokens for tokens of type y. $X_L$ contains both the principal liabilites from taking margin position as well as the interest liabilities from borrowing interest. While a liquidity pool has a claim to its assets and liabilities, only its assets can be used in swaps by future swappers.
### Stateful Metrics
| Name | Description | Symbol |
|----|----|----|
| Leverage | Metric that describes how much a liquidity pool is leveraged, i.e. the ratio of assets to liabilities in the current state | $\eta$ |
| Price | Token price | $P$ |
| Pool Health | Metric describing the health of the MTP liabilities | $H(\mathbf X)$ |
### Stateful Parameters
Stateful parameters are akin to the Parameter dictionary implemented in a Cosmos SDK. Values stored in the parameter dictionary may be constant, but they do not need to be. Methods to update parameter values may be implemented as well.
The Stateful Parameter set is necessary to maintain the Global State of the state variables listed above. Thus, the distinction between the two is nuanced.
| Name | Description | Symbol |
|----|----|----|
| Permit Borrowing | Binary choice to allow borrowing in a liquidity pool | $Allow$ |
| Maximum borrow fee rate | Maximum borrow fee rate that an $mtp$ can incur when it's open. Typically applies to unhealthy $mtp$'s. | $\beta_{max}$ |
| Minimum borrow fee rate | Minimum borrow fee rate that an $mtp$ can incur when it's open. Set by the liquidity pool and typically applies to well performing $mtp$'s. | $\beta_{min}$ |
| Swap fees | Fees applied to swapping in a borrowing enabled liquidity pool | $f(\cdot)$ |
| Margin Maintenance Threshold | Leverage required for margin maintenance | $a$ |
| Default & Covered Threshold | Leverage below which the MTP owner needs to cover their defaulted MTP | $b$ |
| Default & Not Covered Threshold | Leverage below which any agent in the pool can cover the defaulted MTP | $c$ |
| Maximum allowed leverage | Maximum leverage allowed when opening an MTP | $\eta_{max}$ |
| Maximum opening position | Maximum size of position permitted to open an MTP | $\eta_{max}(X)$ |
### Local State ($x$)
Local state is the state necessary for having a legal and active account with a margin trading position ($mtp$). The local state also includes the information necessary for properly interacting with the margin trading system ($MTP$).
The union of the token states of each individual $mtp$ comprises the entirety of the global token state. Thus, if $C = mtp_i: i \in n$, then $C$ is a *cover* of $\mathbf{T}$, because:
$$\mathbf{T} \subseteq \bigcup_{i \in n} mtp_i$$
:::info
In this instance, the term *cover* is in reference to the concept of cover in topology.
**Definition:** A cover of a set $\mathbf T$ is a collection of sets whose union includes $\mathbf T$ as a subset.
The cover $C$ is a collection of $mtp$'s token states. This union $\bigcup_{i \in n} mtp_i$ accounts for the entirety of the global token state $\mathbf T$. Thus $\mathbf T$ is within the union of all $mtp$ token states.
$$\mathbf{T} \subseteq \bigcup_{i \in n} mtp_i$$
Simply put, the global token state is an aggregate of the all of the local token states of liquidity pools that offer $mtp$'s, except the overlaps.
:::
| Name | Symbol | Definition |
| -------- | -------- | -------- |
| Local State | $mtp$ | Individual MTP Position |
| Name | Description | Symbol |
|----|----|----|
| Size of action (x) (asset) | Quantity of tokens of type X used to perform action (collateral)| $x_{A}$ |
| Size of action (x) (liability) | Quantity of tokens of type X in principal liabilities taken on| $x^P_{L}$ |
| Size of action (x) (liability) | Quantity of tokens of type X in interest liabilities accrued| $x^I_{L}$ |
| Size of action (y) (asset)| Quantity of tokens of type Y that are held in custody by taking on liability position in x | $y_{C}$ |
| Current value | Current value of y expressed in terms of x | $\bar x$ |
| Current value | Current value of x expressed in terms of y | $\bar y$ |
| Borrow fee rate | Interest rate applied to a borrow during when an $mtp$ is opened. This rate is $mtp$-specific and event and time varying.| $\beta$ |
| Accumulated Interest fees | Interest fees that accrue over time, payable upon $mtp$ close | $\beta(\cdot)$ |
| Leverage | Leverage multiplier on amount borrowed | $\eta_{mtp}$ |
| MTP State | State of an individual MTP | $\mathbf x$ |
| MTP Health | Metric describing the health of an individual MTP | $h(\mathbf x)$ |
### $MTP$ Health
We can define the health of the margin-enabled liquidity pool as a function of its assets and liabilities: $$ H(\mathbf X) = \frac{X_A}{X_A + X_L} \cdot \eta_{}$$
We can normalize against $\frac{1}{P}$, so that $H(\mathbf X)$ is able to be denominated in either $X$ or $Y$, if $$P_{X \rightarrow Y}:=\frac{\frac{X_A}{X_A + X_L}}{\frac{Y_A}{Y_A + Y_L}},$$
and $$P_{Y\rightarrow X}:=\frac{\frac{Y_A}{Y_A + Y_L}}{\frac{X_A}{X_A + X_L}},$$
then: $$P_{Y\rightarrow X} =\frac{1}{P_{X\rightarrow Y}}$$
We define a threshold $H_{min}(\mathbf X)$. The pool is considered to be unhealthy if it's current health is below the threshold.
$$ H(\mathbf X) < H_{min}(\mathbf X)$$
In this case, the entire pool can force closed via the Forced Global Settlement by Pool mechanism.
### $mtp$ Health
Let's characterize the state of an individual $mtp$ as $\mathbf{x}$.
There is a metric $h(\mathbf{x})\in \mathbb{R}_+$ that captures the health of the asset held in the individual $mtp$.
$h(\mathbf{x})$ is a function of:
- Liability Value $LV_{mtp}$ which describes the amount of obligation, i.e the amount borrowed in the $mtp$
- Asset Value $AV_{mtp}$ which describes the amount of collateral associated with $mtp$ $$h(\mathbf{x}) = \frac{AV_{mtp}}{LV_{mtp}}$$
> An example of a health metric is the collateralization ratio of a Collateralized Debt Position (CDP) as seen in MakerDAO. The [collateralization ratio](https://docs.makerdao.com/dai.js/single-collateral-dai/collateralized-debt-position#getcollateralizationratio) in the CDP is the current USD value of the collateral to the USD value of the Dai in debt.
In the case of an $mtp$ trading $X$ tokens, the health metric is: $$ h(\mathbf{x}) = \frac{x_A}{x_L}$$
We define a partition of the $mtp$'s state space in terms of the metric $h$ based on intervals $(0,c]$ $[c,b]$, $[b,a]$, and $[a,\infty)$. Boundary $a$ is defined by the user, depending on when they would like to be warned about their $mtp$'s health.

- **$mtp$ is healthy**
**State**: The $mtp$ is healthy $$a<h(\mathbf{x})$$
- **$mtp$ is at risk**
**State**: The $mtp$ is at risk $$b< h(\mathbf{x}) \le a$$
- **$mtp$ is in default**
**State**: The $mtp$ is in default. If $c < h(\mathbf x) \le b$, then a liquidation of the $mtp$ holdings would cover the position. If $0 \le h(\mathbf{x}) \le c$, the holdings aren't sufficient to cover the position. In both cases, The $mtp$ can be force settled by a keeper, who earns rewards for triggering forced settlement via the Force Settlement by Any Address mechanism. $$0< h(\mathbf{x}) \le b$$
> **NOTE**
> It's important to note that the difference between the last two states **$mtp$ is in default and covered** and **$mtp$ is in default and not covered** is not necessarily known *a priori* because the holdings may be liquidated but still come up short.
## Action Space
$mtp$ actions are defined as composites of the internal primitive mechanisms as Borrow, Swap, and Repay that are exposed externally to users in the Liquidity Pool Subsystem. This allows for greater modularity in their design.

### Open $mtp$
In order to take a Margin Trading Position (${mtp}$), an agent can perform an ***Open $mtp$*** action.
#### Operational Requirement
> This action can only be performed by an $mtp$ owner, and it can only be perfomed when the $mtp$ is in a *healthy* posterior state.
The Open $mtp$ action is composed of two primitives - Borrow and Swap - using mixed logic.
When an agent performs an Open MTP action,
1. **Borrow**
The agent borrows $x_L = x_A \eta_{mtp}$ amount of X-tokens against collateral $x_A$ which already exists in their wallet. The agent borrows this amount from the Continuous Liquidity Pool (CLP). $\eta_{mtp}$ is the leverage multiplier and $\eta_{mtp} > 0$. $$CLP \overset {borrow \: x_L} \longrightarrow Agent$$
2. **Swap**
The borrowed amount $x_L$ is swapped for $y_L$ amount of Y-tokens, thus creating a long position in the opposite side of the trading pair. This amount is held in the trading account for some duration so as to allow it to appreciate. $$x_L \overset {swap} \longrightarrow y_L$$
This action can be characterized by state variables
- Liability Value $LV_{mtp}$ which describes the amount of obligation, i.e the amount borrowed in the $mtp$
- Asset Value $AV_{mtp}$ which describes the amount of collateral associated with the $mtp$
- Leverage $\eta_{mtp}$ which describes the collateralization ratio of the Borrow action.$$ LV_{mtp} = \eta_{mtp} * AV_{mtp}$$
In this case, the agent borrows $x_L$ as a liability against a collateral of $x_A$ as an asset. So the leverage is $$\eta_{mtp} = \frac{x_L}{x_A}$$
#### Mixing Logic

Mixing logic for determining quantitites of $x$ and $y$ tokens characterized as liability and asset classes:
$\Delta x_A + \Delta x_L = \Delta y_A \cdot f(\cdot)$
#### Opening Position Constraint
The maximum allowable opening position size is defined as a continuous piecewise function where the realized leverage $\bar{\eta}(X)$ of opening a position provides a secondary constraint over the leverage contraint $\eta_{max}$:
$$\eta_{max}(X) = \left \{ \begin{array}{cc}
\eta_{max} & \mbox{for} & \eta_{max}< \bar{\eta}(X) \\ \bar{\eta}(X) & \mbox{for} & \eta_{max} \geq \bar{\eta}(X) \end{array} \right.$$
## Hold $mtp$
Once the $mtp$ starts, the agent accumulates an interest fee $\beta(\cdot)$ , the rate $\beta$ of which is already set by the liquidity pool.
While the agent holds $y_L$ in their trading account, *accumulated interest fee* $\beta(\cdot)$ on the initial borrowed amount $x_L \eta_{mtp}$ accrues over time.
The rate $\beta$ was already set by the liquidity pool.
As the agent accrues interest, their liability grows.
$$LV = x_L + \beta(\cdot)$$
During this phase, the price $P_{Y \rightarrow X}$ of Y-tokens for X-tokens can remain the same, appreciate, or depreciate. The movement of $P_{Y \rightarrow X}$ determines the health of the MTP.
## Close $mtp$
Consider that the agent holds amount $y_L$ of Y-tokens in their trading account, which accrues an interest fee $\beta(\cdot)$ upon **Close $mtp$** on the borrowed amount $x_L$.
In order to close their $mtp$, an agent can perform a ***Close $mtp$*** action. An agent can close an $mtp$ only if it satisfies the **$mtp$ health** condition.
#### Operational Requirement
> This action can only be performed by an $mtp$ owner, and it can only be performed when the $mtp$ is in a *healthy* posterior state.
The close $mtp$ action is composed of two primitives - Swap and Repay.
When an agent performs an Close $mtp$ action,
1. **Swap**
The amount held in the agent's trading account $y_L$ is swapped for its current value in terms of X-tokens, $\bar x_L$ $$ y_L \overset {swap} \rightarrow \bar x$$
2. **Repay**
The agent pays back to the CLP $x_L$ amount of X-tokens, where $\beta$ is the borrow fee on the initial borrowed amount. $$Agent \overset {x_L + \beta(\cdot)} \longrightarrow CLP$$ $$Agent \overset {x_A \eta_{mtp} + \beta(\cdot)} \longrightarrow CLP$$
#### Mixing Logic

Mixing logic for determining quantitites of $x$ and $y$ tokens characterized as liability and asset classes:
$\Delta x_A = (1-f(\cdot)) \Delta y_A - (x_L + \beta(\cdot))$
Upon closing the $mtp$, the agent would net a profit or loss which is the difference between the value of their current holdings and the amount repaid, as well as the borrow fee upon opening the $mtp$. $\Omega$ describes the agent's profit or loss on the $mtp$ $$\Omega_{mtp} = \bar x - (x_L + \beta(\cdot))$$ $$\Omega_{mtp} = \bar x - (x_A \eta_{mtp} + \beta(\cdot))$$
## Margin Maintenance
#### Operational Requirement
This action can only be perfomed by the MTP owner, and it can be performed only if MTP is in the *at risk* or *healthy* states.
This section discusses the permissible action space for MTP holders, given the current state of their position.
### `MTP is healthy` Action Space
**Assumption that $\eta_{mtp, max} \ge a$, then you can borrow up to $\eta_{mtp, max}$ at the time of opening.**
Given this relationship between margin limit $\eta_{mtp, max}$ and health metric region parameter $a$, an opened $mtp$ will remain in this healthy state as long as $$\eta_{mtp} \ge a,$$
where $$\eta_{mtp} = F \cdot a,$$
with $F$ being a factor of safety, where $F > 1$.
#### Close Position
A $mtp$ holder can sell off and close their $mtp$ entirely. The holder incurs a profit. This resolves in a return of collateral with profit less borrow fee $\beta(\cdot)$.$$ \bar{x} = \bar{y} \cdot P_{Y \rightarrow X} - (x_L + \beta(\cdot))$$
where $P_{Y \rightarrow X}$ is the price of token Y with respect to X.
The returned $\bar{x}$ is expected to be greater than the orginal collateral amount $x_A$ resulting in a profit: $$\Omega_{mtp} = \bar x - x_A$$
#### Sell off Liability
A $mtp$ position can sell off some of its liability to decrease their leverage at an amount $y$ where $\Delta{h(\mathbf{x})}$: $$\Delta{h(\mathbf{x})} \ge a - \eta_{mtp} $$
Selling $y$ tokens: $$\Delta{y} \le 0$$
and $$\bar{y}^+ =\bar{y} + \Delta{y}$$
### `mtp is at risk` Action Space
**State**: The $mtp$ is at risk
**Permissible actions**: The MTP owner is allowed to return the MTP to a healthy state when $$b< h(\mathbf{x}) \le a$$
**Requirement**: Impose limit where MTP holders are not permitted to make an action that decreases $h(\mathbf{x})$.
Doing nothing results in decreasing $h(\mathbf{x})$ if there is a nonzero fee function, assuming the price is constant.
The $mtp$ holder is permitted to take an action which increases $h(\mathbf{x})$. $$\Delta{h(\mathbf{x})} \ge 0$$
where $$\Delta{h(\mathbf{x})} ={h(\mathbf{x})}^+ - {h(\mathbf{x})}$$
Constrained to the $\Delta{h(\mathbf{x})}$ limit, this may be accomplished through a series of actions, each of which is valid under this requirement.
It is presumed that the resolved action will improve the position somewhere in the healthy region: $$h(\mathbf{x})^+ \ge a$$
Else, we can consider there to be one action large enough to resolve in $h(\mathbf{x})^+ \ge a$, $$\Delta{h(\mathbf{x})} \ge a - h(\mathbf{x}) $$
If ${h(\mathbf{x})} \approx \eta_{mtp}$ : $$\Delta{h(\mathbf{x})} \ge a - \eta_{mtp} $$
#### Close Position
A $mtp$ holder can sell off and close their $mtp$ entirely. The holder will accept the losses, which are covered with their collateral. This resolves in a return of collateral less trading losses and borrow fee $\beta(\cdot)$.$$ \bar{x} = \bar{y} \cdot P_{Y \rightarrow X} - (x_L + \beta(\cdot))$$
where $P_{Y \rightarrow X}$ is the price of token Y with respect to X.
The returned $\bar{x}$ is expected to be less than the orginal collateral amount $x_A$ resulting in a loss: $$\Omega_{mtp} = \bar x - x_A$$
#### Sell off Liability
A $mtp$ position can sell off some of its liability to decrease their leverage at an amount $y$ where $\Delta{h(\mathbf{x})}$: $$\Delta{h(\mathbf{x})} \ge a - \eta_{mtp} $$
Selling $y$ tokens: $$\Delta{y} \le 0$$
and $$\bar{y}^+ =\bar{y} + \Delta{y}$$
The least amount of $y$ tokens to be sold are: $$ \Delta{y} = \frac{ - (a - x_L - \beta(\cdot))}{P_{Y \rightarrow X}}$$
$$ \Delta{y} = \frac{ - (a - \eta_{mtp}x_A - \beta(\cdot))}{P_{Y \rightarrow X}}$$
:::info
**Interest Liabilities**
$\beta(\cdot)$ forms the interest liabilities, i.e. the liabilities that are accrued over time over the lifetime of the $mtp$ on top of the principal liability $x_L$
$\beta(\cdot)$ is the output of a policy applied on the $mtp$
:::
#### Add Collateral
An $mtp$ holder may increase their collateral position to at an added quantity of $x$ where $\Delta{h(\mathbf{x})}$: $$\Delta{h(\mathbf{x})} \ge a - \eta_{mtp} $$
Adding $x$ tokens: $$\Delta{x} \ge 0$$
and $$\bar{x_A}^+ = \bar{x_A} + \Delta{x}$$
$$ \Delta{x} = [a - \eta x_A - \beta(\cdot)] \cdot P_{Y \rightarrow X}$$
### `mtp is default` Action Space
**State**: The $mtp$ is default
**Permissible actions**: Any address is allowed to force settle the now defaulted $mtp$ when $$0 < h(\mathbf{x}) \le b$$
#### Forced Settlement by Any Address
The Forced Settlement by Any Address action is composed of the primitives - Interest Liability Computation, $mtp$ health computation, Swap, Forced Settlement Rewards, and Repay.
#### Operational Requirement
> The Forced Settlement by Any Address action can be performed by any address in the Liquidity Pool, and it can only be performed when the MTP is in the *default* state i.e. $$0 < h(\mathbf{x}) \le b$$
-----------
[Go back to README](https://hackmd.io/@shrutiappiah/rkOnQeXZ_)