---
# System prepended metadata

title: Sifchain Margin Trading Cryptoeconomics Paper

---

# Sifchain Margin Trading Cryptoeconomics Paper
# Part 1
## To skip to [Part 2](Sifchain_Margin_Trading_Cryptoeconomics_Paper_pt_2.md)

"Health is wealth and we are destined for immortality."

Sifchain enables margin trading, both long and short positions, in cryptocurrencies on its decentralized exchange (DEX). This paper sets out the reasoning, notation, and mechanism specifications that go into the design and implementation of such a system. Sifchain currently uses a slip-based fee to cover the costs of its operation. Margin trading occurs in the Liquidity Provider Subsystem.  The paper also sets out a group of three policies (DEX Liquidity Protection, Ratio Shifting, Liquidity Provider Distribution), which we refer to collectively as Protocol Monetary and Fiscal Policy (PMFP).

The paper begins with a series of tables describing the notation used throughout, and moves into a discussion of the core liquidity provider subsystem. With the LP system specified, the paper moves into a deeper discussion of the Protocol Monetary and Fiscal Policy modules and subsystems. The paper closes out with the specification of the primitive and composite mechanisms that make up the system. To see a more in-depth technical discussion of the mechanisms as they are designed and implemented, refer to the [Margin Trading Implementation Guide](https://hackmd.io/M4y3-r1wTre6zQ4HX8R0Qg#Margin-Trading-Module-Implementation).

Sifchain uses a 2-sided liquidity pool with coins denoted $X$ and $Y$. In documentation, the $Y$ token is understood to be Rowan, Sifchain's protocol token. In practice, $X$ and $Y$ can stand for any token pair. In addition, $MTP$ refers to one of the liquidity pools; $mtp$ refers to an individual margin trading position.

# Table of Contents
1. Variables
2. Liquidity Provider Subsystem
3. Interest Rates, Health, and Liabilities
4. Protocol Monetary and Fiscal Policy
5. Mechanism Specifications

# Variables
The paper contains a mix of prose, mathematics, and pseudocode. In order to maintain consistency both within the document and across specifications, we lay out the notation that will be used throughout.

## Global State for a Single Liquidity Pool

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 | Quantity of tokens of type X as an asset | $X_{A}$ |
| X Principal Liabilities | Quantity of tokens of type X as a principal liabilities| $X^P_{L}$ |
| X Interest Liabilities | Quantity of tokens of type X as interest liabilities | $X^P_{I}$ |
| X Custody | Quantity of tokens of type X held in custody|$X_{C}$ |
| Y Assets | Quantity of tokens of type Y as an asset| $Y_{A}$ |
| Y Principal Liabilities | Quantity of tokens of type Y as principal liabilities| $Y^P_{L}$ |
| Y Interest Liabilities | Quantity of tokens of type Y as interest liabilities | $Y^I_{L}$ |
| Y Custody | Quantity of tokens of type Y held in custody|$Y_{C}$ |  
| X from Oracle | Quantity of tokens of type X from oracle | $X_{\oslash}$ |
| Y from Oracle | Quantity of tokens of type Y from oracle | $Y_{\oslash}$ |

To open a long margin trading position (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 liabilities from opening a margin position as well as the accruing interest liabilities on the borrowed sum in the pool.  While a liquidity pool has a claim to both assets and liabilities, only its assets can be used in swaps by future swappers. Custody is a locked state for tokens that represents the total borrowed position. It serves as the funding source for interest fees, the record of the margin position, and the means to prevent double spending of tokens.

### Stateful Metrics
These are high level metrics used, among other things, to determine the overall health and liquidity of a given pool or trading position.

| Name | Description | Symbol |
|----|----|----|
| Price | Token price | $P$ |
| Pool Health | Metric describing the health of the MTP liabilities | $H(mtp)$ |
| Gain Factor of Pool Health | Gain factor used for borrow fee calculations | ${K_H}$ |
| Pool Ratio Price | Ratio of Quantity of tokens of type X to tokens of type Y in pool | $P_{R}$ |
| Pool Spot Price | Spot price token X to token Y in Liquidity Pool| $P$ |
| Pool Realized Price | Realized price token X to token Y in Liquidity Pool upon a given action| $\bar{P}$ |
| Depth | Depth| ${D_{R}}$|
| External Oracle Price | Oracle price token X to token Y| $P_{\oslash}$ |
| Oracle Depth | Oracle Pool Depth| ${D_{\oslash}}$|

### 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 |
|----|----|----|
| 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}$ |
| Target borrow fee | Upcoming borrow rate is computed for each $mtp$ in a pool applied over next epoch.  | $\beta^{\star}$ |
| Target borrow fee health | Health component of $\beta^{\star}$ | $\hat{\beta}$ |
| Epoch Length | Defined number of blocks (or time) where upcoming borrow rate is computed for each $mtp$  | $T$ |
| Swap fees | Fees applied to swapping in a borrowing enabled liquidity pool | $f(\cdot)$ |
| Initial Threshold | Health level at which an mtp opened | $a$ |
| Default Threshold | Health level for an mtp below which an mtp is in default and can be liquidated.   | $b$ |
| Maximum opening leverage | Maximum leverage allowed when opening an mtp with a given collateral size | $\eta_{max}(x)$ |
| Maximum principal liability | Maximum size of principal liability | $x^P_{L{max}}$ |

## Local State 
Local state is the state necessary for maintaining 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$).

| 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}$    |
| Borrow fee rate                   | Interest rate applied to an $mtp$. This rate is $mtp$-specific and event and time varying. | $\beta(\cdot)$ | 
| Size of action (y) (asset)        | Quantity of tokens of type Y used to perform action (collateral)                           | $y_{A}$    |
| Size of action (y) (liability)    | Quantity of tokens of type Y in principal liabilities taken on                             | $y^P_{L}$ |
| Size of action (y) (liability)    | Quantity of tokens of type Y in interest (excess) liabilities  taken on                    | $y^I_{L}$ |
| Size of action (x) (asset)        | Quantity of tokens of type X held in custody by taking on liability position in y          | $x_{C}$ |
| Gain Factor of MTP Health         | Gain factor used for borrow fee calculations                                               | ${K_h}$ |
| Block (time) count between epochs | Count for borrow fee and interest liability local computation                              | $t$  |
| Leverage                          | Leverage multiplier on amount borrowed                                                     | $\eta_{mtp}$ |
| MTP Health                        | Metric describing the health of an individual MTP                                          | $h(x)$ |
| Forced Settlement Reward Function | Computes the Forced Settlement Reward amount in the case of liquidation                    | $R_{FS}(\cdot)$ |
| Closing value                     | Value of y expressed in terms of x as an mtp is being closed                               | $\bar x$ |
| Closing value                     | Value of x expressed in terms of y as an mtp is being closed                               | $\bar y$ |

## Keeper and Reputation
The Keeper allows positions to be liquidated by the Sifchain protocol in the event that a position becomes impossible to maintain (i.e., that the liabilities far exceed the assets or custodied position).

| Name | Description | Symbol |
|----|----|----|
| Keeper Fund | Funds available in the Keeper, held in multiple assets | $KF$ |
| Keeper Fund Star | Idealized portfolio of the Keeper Fund, set by governance | $KF^*$ |
| Keeper Fund Bar | Minimum size of the Keeper Fund at the beginning of a Keeper Fund Epoch | $\overline{KF}$ |
| Keeper Fund Income Percentage | A portion of interest allocated to KF from each pool | $j$ |
| Keeper Fund Multiplier | Amount of outstanding loans that can exist, expressed as a percentage of KF | $M$ |
| Submersion Price Formula | Formula used to determine the submersion price for an mtp | $S$ |
| Trader Reputation | Amount of reputation available for a user | $traderrep$ |

## Protocol Monetary and Fiscal Policy Variables
The Protocol Monetary and Fiscal Policy modules enable a set of actions and behaviors that help the overall system maintain its health and reward Liquidity Providers. The suite of tools comprises Ratio Shifting, DEX Liquidity Protection, and Liquidity Provider Distribution.

### Ratio Shifting Variables  
#### Chain State
The chain state is the set of information from the consensus protocol. This is exogenous to the model of the liquidity pool in that blocks are validated without the feedback loop that prevents the operation of the protocol. The variables specified below are the state of the chain necessary to be read by the monetary policy.

| Variable Name | Descriptive Name | Description | Symbol |
|----|----|----|----|
| start_block_height | Start Block Height| First block of a given policy period| $h_s$ |
| final_block_height| Final Block Height | Last block of a given policy period| $h_F$ |
| current_block | Current Block | Current block | $h$ |

#### Governance Decision
The governance decision is a policy input message that broadcasts a specified $r_{gov}$ for a specified length of time $l_{policy}$, with a computable $r_{final}$ as the intentional end-state of the policy at the end of its effective life at $h_f$.  

| Variable Name | Descriptive Name | Description | Symbol | Domain |
|----|----|----|----|----|
| epoch_length | Epoch Length | Number of blocks in an epoch (likely to approximate 1 day in practice)| $l_{epoch}$ |
| policy_length_in_epochs | Policy Length in Epochs | Number of epochs in the policy; the specific governance policy period resulting from one particular vote | $l_{policy}$ |
| gov_rate | Governance Rate | Per-epoch (approximately daily) rate of purchasing power increase voted in by governance | $r_{gov}$ |
| final_compounded_rate | Final Compounded Rate | Overall rate of increase over the policy length| $r_{final}$|
| max_rowan_liquidity_threshold_percentage | Max Rowan Liquidity Threshold Percentage| Percentage of Rowan liquidity allowed to move out of a pool in a given epoch | $r_{MAX-LIQ}$ | $0 \leq r_{MAX-LIQ} \leq 1$ |


**Assumption: epoch_length is a governance design, where there is the need for the consensus protocol to execute an epoch module.**

**final_compounded_rate is a metric of gov_rate and policy_length_in_epochs**

#### Liquidity Pool Module State
The liquidity pool receives monetary policies through governance decisions, updating its parameters for $r_{gov}$ and $l_{policy}$. Combining this policy with the production of blocks from the protocol, allows for the computation of $r_{block}$ and $r_{running}$.

| Variable Name | Descriptive Name | Description | Symbol |
|----|----|----|----|
| block_rate | Block Rate| Incremental increase on a per block basis to reach ${final\_compounded\_rate}$ | $r_{block}$|
| running_rate | Running Rate| The purchasing power multiplier rate at a given block | $r_{running}$ |
| $y_o$ | $y_o$ | Rowan ($y$) amount resulting from the swap at the starting time. Calculate the value of $y$ that a user would get if there was no purchasing power increase. | $y_o(x)$ |
| $x_o$ | $x_o$ | Non-Rowan ($x$) amount resulting from the swap at the starting time. Calculate the value of $y$ that a user would get if there was no purchasing power increase. | $x_o(y)$ |
| ALLOW_EXTERNAL_LIQUIDITY_OUT | | Boolean, true if halting action is not met, false if under restriction | $trade_{enabled}$ |
| max_rowan_liquidity_threshold | Max Rowan Liquidity Threshold | Maximum amount of Rowanermitted to move out of a pool at that block, subject to the limit within the epoch | $\tau_{max}$ | $\tau_{max} \geq 0$ |
| current_rowan_liquidity_threshold | | Current allowable Rowan threshold | $\tau_t$ |

### Ratio Shifting Evaluation Metrics
These symbols and notations are specific to the evaluation of the protocol's monetary. 
| Symbol | Name | Meaning |
| -------- | -------- | -------- |
| $G$        | Governance     | Governance decision  |
| $t_{i}(G)$ | Governance start | Beginning timestep $t$ for governance decision |
| $t_{f}(G)$ | Governance finish | End timestep $t$ for governance decision |
| $r$        | Block rate | Governance decision rate |
| $X$        | X pool depth | Depth of the pool in X token |
| $Y$        | Y pool depth | Depth of the pool in Y token |
| $x$        | x token swap | Amount of token X in a swap |
| $y$        | y token swap | Amount of token Y in a swap |
| $\mathcal{G}$ | All Governance | Set of all governance decisions over time intervals |
| $x_{CLP}^G$ | x swap with governance | Amount of x from a swap resulting from Governance |
|$y_{CLP}^G$ | y swap with governance | Amount of y from a swap resulting from Governance |
|$\phi$     | fees | Fees paid into the pool for executing a swap |

# Liquidity Provider Subsystem Overview
Margin trading occurs in the liqiuidity provider subsystem. This enables both long and short positions in two-sided liquidity pools.

### Roles

A liquidity pool consists of two primary actors:
- **Liquidity Providers** who provide Rowan or some other token for a given duration of time to earn rewards.
- **Swappers** who participate in the liquidity pool to swap Rowan for another token or vice versa.

![](https://i.imgur.com/AYTYVwc.png)

## Margin Trading Position Lifecycle

### Open $mtp$

In order to take a Margin Trading Position (${mtp}$), an agent performs an ***Open $mtp$*** action.

> NB: 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 Open $mtp$ action is composed of two primitives - Borrow and Swap - that are described in more detail in the "Mechanisms" section.  

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 liquidity pool. $\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 a separate trading account for some duration so as to allow it to appreciate. The Sifchain protocol has custody over the account; while the agent can take some actions against these funds, he cannot use them for arbitrary purposes not intended for an mtp.  $$x_L \overset {swap} \longrightarrow y_L$$

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}$$ 

### Hold $mtp$
Once the $mtp$ starts, the agent accumulates an interest fee $\beta(\cdot)$ on the initial borrowed amount over time. As the agent accrues interest, their mtp's liability grows.

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.

The agent is able to add collateral beyond the initial collateral they offered to reduce their leverage and increase the health of their mtp.

### Close $mtp$

In order to close their $mtp$, an agent performs a ***Close $mtp$*** action. This action can only be performed by an $mtp$ owner or the protocol itself in the case of liquidation.  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$ is swapped for its current value in terms of X-tokens, $\bar x$ $$ y \overset {swap} \rightarrow \bar x$$

2. **Repay**
The agent pays back to the liquidity pool $x_L$ amount of X-tokens plus accumulated interest. $$Agent \overset {x_L + \beta(\cdot)} \longrightarrow CLP$$ 

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$. $$profit\_or\_loss\_{mtp} = \bar x - (x_L + \beta(\cdot))$$ 

## Overview of Principal Liabilities and Interest Liabilities

We can characterize liabilities into four distinct categories based on their path of execution, how they can be computed, and which entity incurs them. 

### Liabilities in the Global State

Each liquidity pool that offers margin trading takes on $MTP$ Principal Liabilities and $MTP$ Interest Liabilities. 

**$MTP$ Principal Liabilities** are liabilities that the pool captures upon any participant opening an individual $mtp$. This is the running sum of all the borrow amounts $x_L$'s from all individual $mtp$'s opened excluding all the amount repaid, and excluding any interest fee. 

$$
X^P_{L} = \sum\limits_{i=0}^N x^P_{L,i}
$$

where $i$ is the index of individual $mtp$'s and $N$ is the total number of all $mtp$'s currently in the pool.

While the pool theoretically accumulates Interest Liabilities as well, these are paid off continuously and so not considered meaningful for the rest of our calculations. Thus:

$$X_L = X^P_{L}$$

>NOTE:
Interest liabilities are accumulating at the $mtp$ level, but are not considered part of the liquidity pool ($MTP$) liability for this paper.**

### Liabilities in the Local State

Similarly, each $mtp$ owner also takes on liabilities, one of which is set at the time of opening or borrowing more, the principal liabilities, and another that accumulates over time, the interest liabilities.

**$mtp$ Principal Liabilities** are the liabilities that the $mtp$ owner gets upon opening an $mtp$. This is the borrow amount $x^P_L$ that is used to open the $mtp$, excluding any added collateral $x^P_A$ through margin maintenance on the same $mtp$, and excluding all interest fees.

$$ \mathbf{x}^P_{L} = x^P_{L,t} - \sum\limits_{t=0}^{\mathbf t} x^P_{A,t}
$$

At the borrow amount at $t=0$, i.e $mtp$ start is $x^P_{L,0}$. Substituting,
$$ \mathbf{x}^P_{L} = x^P_{L,0} - \sum\limits_{t=0}^{\mathbf t} x^P_{A,t}
$$

where $t$ is the period and ${\mathbf t}$ is the current period. 

> **Note**
> At this time, agents are not permitted to add more liabilities to an existing open $mtp$. If they would like to add liabilities, they can open a new $mtp$ in the same pool.


**$mtp$ Interest Liabilities** are liabilities that the $mtp$ owner incurs over time from the accumulating interest fees $\beta(\cdot)$ owed on their $mtp$. This is the running sum of interest fees incurred by the $mtp$ from each period, less all the already paid interest fees.

$$ 
\mathbf{x}^I_{L} = \sum\limits_{t=0}^{\mathbf t} x^I_{L,t} 
$$

where $t$ is the period and ${\mathbf t}$ is the current period. 

At any given state, the $mtp$ owner's liabilities are a sum of $mtp$ Principal Liabilities and $mtp$ Interest Liabilities.

$$
\mathbf{x}_L = \mathbf{x}^P_{L} + \mathbf{x}^I_{L} 
$$

## Chain State and Full State

The **Chain State** comprises all the state variables, where each of these state variables are computed and updated on-chain with every state change. 

The **Full State** comprises all stateful metrics - global and local. These are higher-order and can be deterministically computed from a set of the latest Chain State state variables polled from the blockchain. The logic for this computation may be housed off-chain, say on the UI, thus improving performance by saving on on-chain computational and storage costs. 

Metrics in the Full State can be calculated via a pre-defined computation that lives in the end-user application layer, akin to Cosmos SDK's `Query` method.  

If **all** information could be computed every block for **nearly no** cost, there would be no need for the distinction between the **Chain State** and the **Full State**. This idealized scenario would result in perfect information knowledge. Decisions on the frequency to call the `Query`, triggering events, and dependent computation updates, such as updates to parameter methods determine the difference in knowledge between the information in the **Chain State** and the information in the **Full State**.

## Analysis of Interest Rates, Health, and Liabilities 

### Target Borrow Fee Domain Mapping from Health Metrics

A borrow rate exists for all $mtp$'s in a given pool that dynamically changes as a result of $H(X,Y)$, the pool health metric, determined by the ratio of assets to the total pool position in the pool. There is a higher interest rate component associated with positive length queues determined by $s(q)$.

$$ \beta^{\star} = \hat{\beta}  + s(q)$$

with 

$$\hat{\beta} = K_H({H(X,Y)})$$

As either of the liabilities grows, $H(X,Y)$ decreases, and the interest rate grows proportionally. Since $K_H$ is defined as a gain factor, its value could be a governance decision or the result of some function on the liquidity pool or the Sifchain protocol.   

Leaving $K_H$ as a tuneable gain factor, and substituting: 

$$H(X,Y) = \frac{X_A}{X_A+X_L} \cdot \frac{Y_A}{Y_A + Y_L} $$

$$  \beta^{\star}  = K_H (\frac{X_A}{X_A+X_L} \cdot \frac{Y_A}{Y_A + Y_L}) + s(q) $$ 
   
A liquidity removal from a pool can cause the health of the pool $H$ to drop if the withdrawal is large enough. To avoid this, there is a governance-set threshold health level, $\bar{H}$, below which liquidity cannot be removed. The part of liquidity removal requests that would cause $H(X,Y)$ to drop below $\bar{H}$ is placed on a waiting list. 

Liquidity withdrawals on this waiting list are disbursed at a point in the future when there is enough liquidity in the pool for the pool's health to stay at or above $\bar{H}$. Denote by $X_A',Y_A'$ the assets in the pool after some withdrawal. Denote by $\theta_t$ the maximum amount of requested liquidity that can be withdrawn on period $t$ such that $H(X',Y') \geq \bar{H}$. $\theta_t$ is distributed proportionally among the requests on the waiting list. Denote the amount of liquidity withdrawals on the waiting list $\omega_t$ at block $t$. 

At time $t$, $q_t$ is defined as:

\begin{cases}
    0 & \text{if } \omega_t = 0 \\
    q_{t-1} + \omega_t & \text{otherwise.}
\end{cases}

Thus $q$ can be interpreted as the sum of the time-value  of all elements that have been in the waitlist since it last cleared (either $x$ or $y$) in a common denomination (Rowan). The natural unit for this is Rowan blocks of queued assets. For example, 5 Rowans worth of tokens queued for 1 block is equivalent to 1 Rowan queued for 5 blocks. 

$$
s(q) = \min{ ( a\cdot q , s_{\max})} 
$$


Interest on an $mtp$ for the current epoch, $\beta$, is designed to approach a target interest rate, $\beta^\star$, in a manner described in the "Borrow Fee Between Epochs" section below. As discussed above, $\beta^\star$ is itself composed of a health metric, $\hat{\beta}$,  and the queue status,  $s(q)$. For now, we will focus on the target interest rate itself, $\beta^\star$.

The target interest rate, $\beta^\star$ will exist between two bounds set by the liquidity pool as parameters:
$$ \beta_{min} \leq \beta^\star \leq \beta_{max}$$ 

As a pool's total liability approaches 0 ($X_L \to 0$), its health approaches 1 ($H(X) \to 1$).  A pool with $X_L = 0$ would have no open $mtp$s.  As $H(x) \to 1$, we expect $\beta^\star \to \beta_{min}$. An $mtp$ with unbounded growth in its liability position ($X_L \to \infty$), its $H(x) \to 0$.  As $H(x) \to 0$, we expect $\beta^\star \to \beta_{max}$. 


### Borrow Fee Between Epochs 
At each epoch $T$, the target borrow fee $\beta^{\star}$ for the next epoch is computed and broadcast for each open $mtp$.

At the start of each epoch, $t=0$ and $\beta_t \approx \beta^{\star}_{T-1}$. At the end of each epoch, $t=T$ and $\beta_t \approx \beta^{\star}_T$.

During each epoch, we want $\beta$ to move toward $\beta^{\star}$, where the difference between the previous borrow fee and the target and the rate of update are the expected inputs:

$$ \beta^+_t = f(\beta^{\star}_T , t)$$

Under an assumption of decreasing rate of change $\beta^+_t$ during the epoch, we can allow local computation of the borrow fee in this manner:
$$\Delta \beta_t = (\beta^{\star}_T - (\beta^{\star}_{T-1}) \cdot \frac{\ln(2)}{t \cdot \ln(T)}$$
for $T >1$, and where the term $\frac{\ln(2)}{\ln(T)}$ is a constant for any $T$. 

### Effects of Liquidity Pool Actions on Borrow Fee 
Available liquidity (function value) as well as add and remove liquidity actions (derivative) are expected to affect $H(X,Y)$ and subsequently effect $\beta$. Likewise, opening and closing an $mtp$ will also effect $H(X,Y)$ and $\beta$. We can explore both cases with partial derivatives, where there is an action taken on $X$ and we resolve the metric:

$$ \frac{\partial\beta}{\partial X} = \frac{\partial}{\partial X} f(H(X,Y))$$

If we use the version from the previous section where $K_H$ is a tuneable gain factor:
$$f(H(X,Y))=  K_H \cdot \frac{X_A}{X_A+X_L} \cdot \frac{Y_A}{Y_A + Y_L} $$

### Accumulated Interest Liabilities Domain Mapping
The interest liabilities for each position $mtp$ is the accumulated interest fee for that position.

$x^I_{L}$ is a function of:
 $$ x^I_{L,t} = f(\beta_t, x_{L,t}) $$
 
$$ x^I_{L,t+1} = \beta_t \cdot (x^I_{L,t}+x^P_{L,t}) $$
 
Interest liabilities can computed be from $x^P_{L,0}$. 

$$x_{L,t} = x^P_{L,0} + x^I_{L,t-1}$$

So the interest liabilities at $t$ are
$$ x^I_{L,t} = f(\beta_t,x^P_{L,0} + x^I_{L,t-1})$$
for $t>1$.
 
Computed as an integral for each successive block where each rectangular area segment is the $\beta \cdot x_L$

### Interest Liabilities between Epochs
At the individual $mtp$ level, interest liabilities $x^I_L$ need to be a part of the Chain State at the epoch level, as the calculation of $mtp$ health $h(x)$ is contingent on it.

$\beta^*$ and $h(x)$ will be computed at every epoch. Thus, $x^I_L$ needs to be polled once per epoch. Within an epoch, $x^I_L$ accumulates off-chain. It is realized on-chain at the start of the next epoch. To summarize,
- $x^I_L$ is in Chain State at the epoch level
- $x^I_L$ is in Full State within an epoch

### Effects of interest liabilities on $mtp$ health
At the epoch level, as interest liabilities accumulate, $mtp$ health deteriorates.

$$ h(x) = \frac{x_A}{x_A + x_L}$$

The decline in $h(x)$ affects the steady state interest rate $\beta^*$ as 

$$ \hat{\beta} =  K_H(H(X,Y))$$

**Thus, within an epoch** $\hat{\beta}$ is an *attractor*. $K_H(H(X,Y))$ is akin to a base rate applied to all $mtps$ in the pool and forms a *global attractor*. This global state and the leverage and assets of the individual $mtp$ fully determine their interest liabilities.

### Interest Paid From Liquidity Pool to Keeper Fund

While an $mtp$ is open, interest liabilities are accumulated by it and paid off block-by-block to the liquidity pool.  However, a percentage of those interest liabilities are then paid from the liquidity pool to the Keeper Fund (described more below).  The exact percentage is set by governance.


# $mtp$ Health and Liquidation

We define a partition of the $mtp$'s state space in terms of the metric $h(x)$ based on intervals $(0,c]$ $[c,b]$, $[b,a]$, and $[a,\infty)$. 

- **$mtp$ is healthy**
**State**: The $mtp$ is directionally positive.  It is healthier and more profitable than when it was opened. $$a<h(\mathbf{x})$$

- **$mtp$ is at risk**
**State**: Effective $mtp$ leverage > initial $mtp$ leverage.  The position is less healthy and less profitable than when it was opened $$b< h(\mathbf{x}) \le a$$

- **$mtp$ is submerged**
**State**: The $mtp$ is submerged.  At this point, closing the $mtp$ would not lead to a full repayment to LPs without assistance from the Keeper Fund.  To ensure LPs remain whole, if the $mtp$ is closed in this state then the Keeper Fund will indeed keep LPs whole. $$c< h(\mathbf{x}) \le b$$

- **$mtp$ is liquidated**
**State**: The $mtp$ is liquidated.  At this point, the Keeper will forcibly close the $mtp$ and use the Keeper Fund to ensure LPs remain whole.  $$ h(\mathbf{x}) \le c$$

## Liquidation and Submersion

Many cryptocurrencies are so volatile that a standard liquidation system would make them untradeable with deep margin. Sifchain's submersion system resolves that issue.  Subject to protocol governance of the Keeper (described in more detail below), the price at which a position is liquidated is based on a time-weighted average price rather than the current price. An $mtp$ whose swap price has gone below the liquidation price but whose time weighted average price is above the liquidation price is considered submerged but not liquidated.

![](./images/price_smoothing.png)

In the example above, transient volatility temporarily brings the swap price (red/green candlesticks) below the liquidation price (heavy black line) but because the time weighted average price (thin blue line) doesn't go sufficiently low, the position is not liquidated and can close in profit.  The exact time weighted average price formula is subject to iteration and research from governance and is a function of trader reputation (described more below).

$$ S = f(x_{traderrep})$$

## Cross-Margin

When a user opens a new $mtp$, they have the ability to use profits from an open position as collateral for their new position.  The mechanisms include take_out_of_custody (on old position) -> swap_close (on old position)-> open_mtp (on new position).  No maintenance repay occurred, so $h(oldmtp)$ will go down as $x_A$ will decrease while $x_L$ will remain constant. 

Cross-margin is also used when an mtp is submerged.  The liquidation engine will check to see if any other healthy mtps exist in which case they will be forcibly reduced in size to get collateral to stop the submersion.  The mechanisms include take_out_of_custody (on healthy position) -> swap_close (on healthy position)-> maintenance_repay (on unhealthy position).

## Keeper

The Keeper is the method by which $mtp$s are forcibly closed by the Sifchain protocol.  

The Keeper executes two functions:
- Force closure of errant $mtp$s, 
- Correction of liquidity pool assets and prices immediately after a forced closure

The Keeper is connected to a Keeper Fund which receives a percentage of all interest paid from $mtp$s to liquidity pools.  The Keeper Fund's address is controlled by the Sifchain protocol.

The Keeper is a singular entity that acts on behalf of the protocol; no other agent is able to close errant $mtp$s.

### Policies for Errant mtps

The Keeper tracks all open $mtps$ in order of health $h(x)$.  If $h(x) < b$ for any $mtp$ (meaning it is submerged and at risk of liquidation), the Keeper will iterate through a series of options to avoid a liquidation.

These steps include (in order):

1.  Use cross-margin to scale down other open $mtps$ from the same trader address to provide additional collateral for the errant $mtp$
    a. Allow the $mtp$ to be submerged
    b. If the position falls to liquidation: 
        i. Forcibly close the $mtp$, unwind the swap, and return the borrowed assets to the pool 
        ii. Execute a price-correction swap in the opposite direction of the liquidation
        iii. Add liquidity to the pool to be owned by the LPs in the pool proportionate to their pool shares 

To elaborate on 1.b.ii, after any forced $mtp$ closure, assets from the $mtp$ are swapped in a way that can provide a profitable trading opportunity for other users.  Absent the Keeper taking a price correction swap, malicious validators could organize transactions in such a way as to favor liquidations and then execute a profitable trade.  However, the Keeper can swap immediately after a liquidation to correct the price.  Here, the difference between the post-liquidation pool price $P$ and the estimated true price (obtained from a moving average $P_{MA}$) is used to correct the pool price in the next state following an $mtp$'s forced settlement. The specific moving average formula can be selected and modified by governance.

To elaborate further on 1.b.iii, a position that is submerged and then liquidated will likely not have enough collateral to make liquidity providers whole with its liquidation swap.  The Keeper makes up the difference by allocating funds from the Keeper Fund to the liquidity pool.

### Keeper Fund

The Keeper Fund can contain a portfolio of any assets selected by governance in any sizes deemed appropriate.  In a case with no liquidations, the Keeper Fund is constantly growing because LPs pay the Keeper Fund a percentage, $j$, of interest for every open position.

$$ KF = j *  \sum_{1}^{n} x_{Ia} $$

The Keeper Fund is intended to be a neutral entity designed to prevent MEV and keep liquidity providers whole rather than one that makes directional bets on the future of the market.  The idealized allocation of this portfolio is defined by governance and the Keeper Fund is constantly rebalancing assets to get towards it.

More formally, consider the Keeper Fund (KF) a portfolio with a quantity (potentially 0) of all possible assets on Sifchain.

$$ KF = \{\psi_1, \psi_2, \psi_3, ..., \psi_m\} $$ where $\psi_a$ KF's percentage allocation of the $a$th token on Sifchain.  $\sum_{1}^{m} \psi_a = 1$.

Consider KF's idealized allocations another with a quantity (potentially 0) of all possible assets on Sifchain.

$$ KF^* = \{\mu_1, \mu_2, \mu_3, ..., \mu_m\} $$ where $\mu_a$ KF's percentage allocation of the $a$th token on Sifchain.  $\sum_{1}^{m} \mu_a = 1$.

$$|\psi_a - \mu_a| = e_a$$

At each timestep, the Keeper Fund executes one or more trades to reduce $e_a$ for each token.  Governance can set a time duration, $T_{KFa}$ by which $e_a = 0$ if no $mtp$s are open (meaning no liquidations occur and no liquidity pools give revenue to KF) and the price of each asset remains constant. Governance is expected to pick this duration based on the trading volume and depth of a pool so that the Keeper Fund is not meaningfully moving the market during individual swaps (perhaps 1-7 days in block time).  Moreover, because prices are likely to change over time and people are likely to open $mtp$s at arbitrary times, the $KF$ and $KF^*$ will change often and $e_a$ will rarely if ever equal 0.

### Limitations Imposed by the Keeper Fund

The Keeper Fund enables Sifchain to make LPs whole if an $mtp$ is liquidated or closed while submerged.  It takes on some risk by guaranteeing these properties, which affect all Rowan holders.  Sifchain governance has the ability to inflate the Rowan token to ensure that the Keeper Fund has enough assets on hand to keep LPs whole.  This enables the protocol to make strong statements about how much the Keeper Fund can enable a lucrative trading market but it also opens the risk of unskilled or malicious traders or LPs inducing massive inflation and devaluing Rowan.

At the start of a Keeper Fund Epoch (say 30 days in block time, for example) Sifchain governance decides the total size of the Keeper Fund, $\overline{KF}$.  If the Keeper Fund enters that voting period without a sufficient amount of capital, Sifchain governance can decide to reduce that epoch's coverage by reducing the size of the Keeper Fund. It can also decide to inflate a sufficient amount of Rowan to increase, $\overline{KF}$.

Separately, Sifchain governance can decide to limit the total amount of capital borrowed by margin traders, on both a per-pool basis or across multiple pools).  It can do so in relation to $\overline{KF}$.  Setting 

$$
\overline{KF} = M * \sum_{1}^{n} x_{Pa} + x_{Ia}
$$ 

for a full Keeper Fund Epoch means that margin traders borrow no more than M% of the value in the Keeper Fund at one time.  If there is $100 million worth of cryptocurrencies in the Keeper Fund and $M = 150%$, margin traders can only open a new $mtp$ if no more than $150 million worth of loans are currently outstanding across principle liabilities and interest liabilities.  

This restriction limits the amount of coverage the Keeper Fund can be expected to provide and thus limits risk of inflation to Rowan holders.  How high or low this percentage is set (especially whether it is above or below 100%) will be a reflection of Sifchain's governance's expectations on interest revenue from traders and the risk of liquidation from those same traders.  If the traders are skilled, they'll provide a lot of interest revenue and few liquidations, meaning M can be set very high to maximize revenue.  If the traders are unskilled, they'll provide little interest revenue and many liquidations, meaning M should be set low to minimize risk.  

The Sifchain protocol provides ample room for Sifchain's governance to analyze trader activity and computationally project future market behavior to let it optimize M from one Keeper Fund Epoch to the next.  In the unfortunate event that a market crash or attack occurs and causes the Keeper Fund to need to cover more than $\overline{KF}$ in loans then inflation should still be used to keep LPs whole so that they feel safe pooling on Sifchain but no new mtps can be taken out during the Keeper Fund Epoch, giving Sifchan governance time to analyze market conditions without further risk of inflation from additional mtps.  They can then set $\overline{KF}$ against their updated risk profile.

### Reputation 

Since the Sifchain protocol has data on trader behavior, it can skew the Keeper Fund's usage towards traders who have a history of providing strong interest and few if any liquidations.  We quantify this history as "reputation."

The reputation feature enables submersion to exist in Sifchain's liquidation engine.  Increasing reputation increases the amount of submersion available to a user by limiting the mount of leverage they can take.  

$$ \eta_{max} = f(trader rep) $$

In this case, the exact formula is subject to governance deliberations.

The reputation system accounts for a given trader's use of submersion coverage from the Keeper Fund.  Simply, the less a trader needs to use these funds, the higher their reputation will be. More formally:

$$ trader rep = \max ( 0, \sum_{1}^{v} x_{Ia} - tpsc)$$ where $tpsc$ means "trader's previously used submersion coverage." 

If reputation falls below 0, a trader is incentivized to create a new address with 0 trader rep rather than trade with a negative reputation.  However, only skilled traders with proven records can achieve high reputation and access to higher amounts of leverage and submersion in the system.  

The protocol ensures that submersion does not allow a trader to get more in Keeper Fund coverage than they contribute in interest revenue for poolers.  Unskilled traders who cannot contribute a large amount of interest revenue to the protocol cannot get much submersion coverage and thus cannot drain the Keeper Fund.  Skilled traders can potentially fail with high leverage positions and incur large submersion, but doing so decreases their reputation substantially and reduces the amount of leverage they can take out until they regain their reputation.  

### Lending and Borrowing Reputation

Sifchain governance will want the reputation feature to quickly and decisively increase the reputation of skilled traders so that they can increase their leverage and provide increasing amounts of interest revenue, while denying that privilege to lower skilled traders and avoid risk to the Keeper Fund. Therefore, it offers a reputation lending market place to incentivize skilled traders to identify other skilled traders and monetize their growth.

While traders are limited to an amount of leverage based on their reputation, they can borrow a specific amount of reputation from one or more other traders for a fee set by a lender.  Thus a more complete formula for max leverage is: 

$$ \eta_{max} = f(trader rep[borrowed + owned]) $$

Consider a trader with 500,000 trader rep.  He can choose to lend 10,000 trader rep to a borrower for 4000 Rowan (stored in escrow until the end of the trade).  The borrower will be able to use that 10,000 trader rep to increase available leverage.  If the trade goes successfully, the lender will receive the lending fee of 4000 Rowan.  If the trade goes unsuccessfully, the lender and borrower will both lose reputation proportionate to the amount of submersion coverage the borrower took, and the lending fee will be burned.

## To continue reading [Part 2](Sifchain_Margin_Trading_Cryptoeconomics_Paper_pt_2.md)