Paulina Weiss
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Effects of static and dynamic fees in the HydraDX omnipool ###### tags: `Hydra` `Impermanent Loss` `fees` `TE Academy` > Note to team: > (1) Where there is a pin( :pushpin: ) add tables from Jupyter Notebook. > (2) Add Oracle for HDX, fee revenue basket for HDX in Code. > (3) Add AW plot in plot_utils.py ## Introduction ### Impermanent Loss in Liquidity Pools Internal invariances set in the **Automated Market Maker (AMM)** of a liquidity pool work towards maintaining a stable pool by, for example, incentivising trade such that assets may not be undersupplied or drained from the pool. However, due to price volatility of the risk assets in external markets there can be an arbitrage incentive whenever the local exchange price in the pool deviates from the external market. This arbitrage effect can produce **impermanent loss (IL)** and drain real value from the liquidity pool. A **trading fee** can work to mitigate the risk of IL. It compensates liquidity providers for the expected impermanent loss (i.e. re-distribute external arbitrage profit from arbitrageurs to liquidity providers) thereby increasing return on investment (ROI) and discouraging arbitrage related trades. ### Research Question How can a dynamic fee mechanism mitigate value drainage caused by impermanent loss in liquidity pools without deterring business-as-usual-traders? ### Outline In this document we will... 1. define the **metrics** Impermanent Loss (IL) and, alternatively, the Arbitrage Wedge (AW), 2. define a **baseline** condition in which IL and AW are calculated in the cadCAD Model based on different price oracles without trading fee, 3. test different **static fee schedules** against the baseline, 4. test a **dynamic fee schedule** against the baseline. ## Defining Impermanent Loss (IL) and, alternatively, the Arbitrage Wedge (AW) To compare the effects that different static (dynamic) fee mechanisms have on liquidity pool value we choose two metrics: **Impermanent Loss (IL)** and, alternatively, an **Arbitrage Wedge (AW)**. We assume that external market prices of pool assets change from t= 0 to t= 1 and arbitrage behaviour acts as to balance the pool prices. ### Impermanent Loss (IL) Impermanent Loss (IL) can be defined as the difference of the alternatives in terms of the holding value, i.e. the "loss in value of an asset portfolio held in a liquidity pool compared to the alternative of holding those assets in a private account (i.e. outside the liquidity pool)" (cf. https://hackmd.io/hzvgC7-TQaqtxDY-HudABA?view#A-derivation-of-Impermanent-Loss-IL). $$ IL = \frac{V_1-V_H}{V_H} $$ where V1 is the value of the asset portfolio inside the pool at t= 1 and VHis the value of the asset portfolio outside the pool at t= 1. ### Arbitrage Wedge (AW) More generally, we can quantify the impacts arbitrage can have on the total pool value by calculating an arbitrage wedge (AW). The arbitrage wedge compares the total value of shares in the pool at any time step t had they been held outside the pool ($Total VHt$) and the total value of the liquidity pool $Total V1t$, i.e. the real value of all shares inside the pool at time t). It is defined as the loss in value of **all** asset portfolios held in a liquidity pool compared to the alternative of holding **all** assets outside the liquidity pool).That is, $IL =AW$ if there is only one liquidity provider. $$ AWt = \frac{Total V1t -Total VHt}{Total VHt} $$ $$ Total V1t = \sum\nolimits_{i=1}^N Quantity Asset_it * External Market Price_it $$ $$ Total VHt = \sum\nolimits_{j=1}^t\sum\nolimits_{i=1}^N Quantity AssetAdded_i * External Market Price_it $$ ## Baseline This section defines a **baseline** condition in which IL and AW are calculated in the cadCAD Model based on different price oracles without trading fee. ### Price Oracles We define oracles for the external market price of each risk assets and HDX based on a constant function, a Dirac delta function, a random stochastic function and a random Gaussian function. ```python def constant_function(x, constant=0): """ Returns a constant value `a` such that f(x) = a. Parameters ============ x: the input value. constant: the constant value. """ return constant ``` ```python def dirac_delta_function(x, steps=[(1, 1)]): """ Returns a Dirac delta function such that f(x) = y_0 if x = x_0, y_1 if x = x_1, ... else 0 Parameters ============ x: the input value. steps: a list of deltas. """ for x_n, y_n in steps: if x == x_n: return y_n else: return 0 ``` ```python def random_stochastic_function(x, delta): """ Creates a random stochastic function that adds a value between [-delta, delta] Parameters ============ x: the input value. delta: defines the range """ return (np.random.random_sample() * 2 * delta) - delta ``` ```python def random_gaussian_function(x, sigma): """ Samples from a Gaussian distribution. Parameters ============ x: the input value. delta: defines the variance of the Gaussian curve. """ return np.random.normal(0, sigma) ``` ### IL and AW plots for Oracle sweeps We sweep over all oracles (oracles = [constant function, Dirac delta function, random stochastic function and random Gaussian function]) in the cadCAD model and output IL and AW. :pushpin: TBD ##### No Fee with Constant Oracles $i < j$ ![](https://i.imgur.com/Z4Zq5cy.png) ![](https://i.imgur.com/b4be0As.png) ##### No Fee with $i$ as Increasing Step Function ![](https://i.imgur.com/4pygMJ0.png) ![](https://i.imgur.com/AbvjIuD.png) The price of $i$ increases by $0.3$ at timestep $100$. ##### No Fee with $\Delta i$ from a Random Uniform Distribution ![](https://i.imgur.com/sMGtcM0.png) ![](https://i.imgur.com/WTAyjhs.png) The maximum change in price of $i$ is $\pm0.3$. ##### No Fee with $\Delta i$ from a Random Gaussian Distribution ![](https://i.imgur.com/ndtCi6f.png) ![](https://i.imgur.com/jn4QVWA.png) ## Static Fees This section tests different **static fee schedules** against the baseline. A transaction fee can be implemented by subtracting a percentage of the to-be-traded asset ribefore the swap with another asset and adding to a Fee Revenue Basket in the pool. In the cadCAD model a static fee g(a) with a = [.01, .02, .05] is implemented by swapping $rNew_i = (1-g(a))* r_i$ and adding $FeeRev_i= g(a)* r_i$. The revenue from a fee system can act to balance the potential loss in total pool value due to arbitrage. Total Fee Revenue can be defined as the sum of the quantity of all assets that have been collected as trading fee until time t ($FeeRev_i$) at market prices: $$ Total Fee Revenue_t = \sum\nolimits_{j=0}^t\sum\nolimits_{i=1}^N FeeRev_{ij}* OraclePrice_{it} $$ where N: number of assets in pool. ### IL and AW plots for static fee sweeps We sweep over all static fee schedules (a = [.01, .02, .05] ) in the cadCAD model and output $Total Fee Revenue_t$, as well as plots for IL and AW. :pushpin: TBD ##### Static Fee $a = 1\%$ ![](https://i.imgur.com/O0mdqTy.png) ![](https://i.imgur.com/RbXV8IP.png) ##### Static Fee $a = 2\%$ ![](https://i.imgur.com/xjvBUgq.png) ![](https://i.imgur.com/R19hGTA.png) ##### Static Fee $a = 5\%$ ![](https://i.imgur.com/A3iDxoX.png) ![](https://i.imgur.com/NT17FrM.png) ## Dynamic Fees This section tests a **dynamic fee schedule** against the baseline. Let there be a **dynamic fee based on discrepancy of external market asset price** (i.e. $OraclePrice_{it}$) and liquidity pool asset price ($p_{it}$) at time t: $$g(a)=(1+\mid p_{it}-OraclePrice_{it}\mid)*a$$ **Example**: If $a = .01$, $p_{it} = 2$, $OraclePrice_{it} = 2.5$, then $g(.01)=.015$. Alternatively, we can define a dynamic fee that extracts the arbitrage profit of each trade. $$g(a)=(1+Arbitrage Wedge_{t+1})*a$$ ### IL and AW plots for dynamic fee sweeps We sweep over the dynamic fee schedules (a = [.01, .02, .05] ) in the cadCAD model and output $Total Fee Revenue_t$, as well as plots for IL and AW. :pushpin: TBD ##### Dynamic Fee $a = 1\%$ ![](https://i.imgur.com/Wu0Cu8j.png) ![](https://i.imgur.com/wLjFoX0.png) ##### Dynamic Fee $a = 2\%$ ![](https://i.imgur.com/QtzWmKu.png) ![](https://i.imgur.com/6COaAYe.png) ##### Dynamic Fee $a = 5\%$ ![](https://i.imgur.com/i677xG1.png) ![](https://i.imgur.com/Pbf3uJh.png) ## Analysis and Conclusions :pushpin: TBD ## Appendix ### AW Plot AW Plot in: plot_utils.py ```python def AW_plot(experiments,test_title,T): """ This function plots the Arbitrage Wedge (AW) a metric that defines overall potential IL in the pool due to external market prices. """ AW = [] #Define timesteps as seen in plot_utils.py df = experiments df = df[df['substep'] == df.substep.max()] df.fillna(0,inplace=True) df.reset_index() #Iterate through timesteps and calculate AW for each time step. for i in range(df.substep.max(),T, df.substep.max()): #Get Quantities for all assets in the pool and in the fee revenue basket. Ri = df.pool[i].pool['i']['R'] #+ df['fee_revenue'][i]['i'] Rj = df.pool[i].pool['j']['R'] #+ df['fee_revenue'][i]['j'] Q = rdf['Q'][i] #+ df['fee_revenue'][i]['Q'] #Get Quantities for all shares. Si = df.pool[i].pool['i']['S'] Sj = df.pool[i].pool['j']['S'] Sq = rdf['Sq'][i] #Get external market prices. #oracles = rdf[['oracle_price_i', 'oracle_price_j', 'oracle_price_Q']] MPi = 1 #oracles['oracle_price_i'] MPj = 2 #oracles['oracle_price_j'] MPq = 1 #oracles['oracle_price_Q'] #Calculate Arbitrage Wedge. Total_V1t = Ri*MPi + Rj*MPj + Q*MPq Total_VHt = Si*MPi + Sj*MPj + Sq*MPq AWt = (Total_V1t -Total_VHt) / Total_VHt AW.append(AWt) mathAW = np.array(AW) #Plot Arbitrage Wedge across timesteps. #plt.figure(figsize=(20,6)) #plt.subplot(141) plt.plot(df.timestep, mathAW) plt.xlabel('Timestep') plt.ylabel('Arbitrage Wedge') plt.legend() ``` ### IL Plot IL Plot in: plot_utils.py ``` python def impermanent_loss_plot(rdf): pool = rdf.pool oracles = rdf[['oracle_price_i', 'oracle_price_j']] def get_price(pool, key): return pool.get_price(key) price_i = pool.apply(get_price, key='i') price_j = pool.apply(get_price, key='j') impermanent_loss_i = (price_i - oracles['oracle_price_i']) / oracles['oracle_price_i'] impermanent_loss_j = (price_j - oracles['oracle_price_j']) / oracles['oracle_price_j'] plt.figure(figsize=(20, 6)) plt.subplot(121) plt.plot(impermanent_loss_i) plt.xlabel("Timestep") plt.ylabel("Impermanent Loss") plt.subplot(122) plt.plot(impermanent_loss_j) plt.xlabel("Timestep") plt.ylabel("Impermanent Loss") ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully