0xProtosec
    • 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

      This note has no invitees

    • 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

    This note has no invitees

  • 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
    # GMX Price Feed Explainer The following notes explain the GMX Protocol's price fetching mechanism. The primary aim to convey a sense of the price fetching mechanism and execution flow as it is used by the GMX protocol. ## Introduction The `Vault` is one of the central contracts of the GMX protocol. It allows users to deposit funds into the vault and mints them `GLP` tokens. In addition to withdrawing their assets from the vault, users can also swap tokens, short and long (bet on asset prices, whether they will fall or rise) using leverage. Users get liquidated if losses of the position reduce the collateral's value to the point where `position size / deposited collateral` is more than the `max` allowed leverage. This makes asset price fetching very important. Price fetching done through two contracts: `VaultPriceFeed` and `FastPriceFeed`. ## Price Calculation Overview `keeper` bots calculate asset prices by averaging the prices of said asset on Binance, Bitfinex and Coinbase. There are two types of keeper bots: 1. **PriceFeedKeeper**: Submits prices for swaps routinely (every 2 hours) 2. **PositionKeeper**: Submits prices when a position is being executed. Prices submitted from keepers are not used in two cases (i.e., chainlink prices are used instead): 1. It has been more than 5 minutes since the last keeper price submission. 2. The keeper prices deviate by more than the `maxDeviationBasisPoints` (currently 1000 so 10%) in which case a spread will be used. See further below. There is also a element called `maxDeviationBasisPoints` (currently 1000 so 10%). This is the historical max deviation of the prices supplied by the keepers from the chainlink price. If the prices supplied by the keeprs deviate by more than 10% from the chainlink price e.g., CL is 100 and keeper price is 111, then a pricing spread would be created: 100 and 111. This pricing spread will then be used as follows: 1. Long Position: High price used when opening, low price used when closing. 2. Short Position: Low price used when opening, high price when closing. There are also `Watcher` bots which monitor `Keeper` bots for irregular conduct. If it is noticed, then `Watcher` bots can enforece a spread even if the keeper bots are submitting prices that are within max deviation and are not stale. All prices are multiplied by `1e30` or `10**30` to increase precision. 1 USD is thus equal to `1e30`. Basis points are also used to account for finer movements in prices and values. `10000` is the BPSDivisor, the max spread bps is 50, max adjustment interval is 2 hours and max adjustment bps are 20. There is another contract called `FastPriceFeed` which is used as a secondary price feed. The prices returned from this contract's `getPrice` function are ones that are submitted by the keeprs and are to be used if there are none of the issues mentioned above which either force use of the chainlink price or the spread. The `maximise` bool is used to return the higher or lower of the spread price. This above is explained below in detail along with the execution steps. ## Price Fetching Flow: **Contracts in consideration:**: 1. `VaultPriceFeed`: 0x2d68011bcA022ed0E474264145F46CC4de96a002 2. `FastPriceFeed`: 0x11D62807dAE812a0F1571243460Bf94325F43BB7 **VaultPriceFeed Relevant State**: (*31Dec2022*) `useV2Pricing`: false `isAmmEnabled`: false `isSecondaryPriceEnabled`: true `secondaryPriceFeed` aka `FastPriceFeed` `MAX_ADJUSTMENT_INTERVAL`: 2 hours (7200s) `MAX_ADJUSTMENT_BASIS_POINTS`: 20 BPS (0.2%) `MAX_SPREAD_BASIS_POINTS`: 50 BPS (0.5%) `BPS_DIVISOR`: 10000 (100%) `maxStrictPriceDeviation`: 10000000000000000000000000000 OR 1e28 **FastPriceFeed Relevant State**: (*31Dec2022*) `MAX_PRICE_DURATION`: 30 minutes (1800s) `priceDuration`: 5 minutes (300s) `maxPriceUpdateDelay`: 1 hr (3600s) `isSpreadEnabled`: false `spreadBasisPointsIfChainError`: 500 (5%) `spreadBasisPointsIfInactive`: 2 (0.2%) `maxDeviationBasisPoints`: 1000 (10%) **Functions in consideration:** 1.`VaultPriceFeed.getPrice(address _token, bool _maximise, bool _includeAmmPrice)` 2.`FastPriceFeed.getPrice(address _token, uint256 _refPrice, bool _maximise)` ### Looking into `getPrice` The following happens when a call to `VaultPriceFeed.getPrice(_token, _maximise, _includeAmmPrice)` is made: 1. Fetch the token price from Chainlink (via `getPrimaryPrice(_token, _maximise))`, use the highest/ lowest out of 3 rounds depending on the maximise bool passed. 2. If `isSecondaryPriceEnabled` is true (it is), use the other contract`FastPriceFeed.getPrice(_token,price,maximise)` to calculate and use a price. We now look at `FastPriceFeed.getPrice` where the process goes after step 2. This function is supplied 3 arguments: a. The token address b. The reference price for the given token as fetched from Chainlink in `VaultPriceFeed.getPrice()`. c. The maximise bool, whether to return the higher or lower price in case a spread is used. 3. If it has been more than 1 hr since the price was last updated, convert price to BPS (multiply by `BPS_DIVISOR` - 10_000BPS) add `spreadBasisPointsIfChainError` (500BPS so 5%) to it and divide by BPS_DIVISOR and this is the price. 3.1. If it has not been more than 1 hr since last price update, then if it has been more than `priceDuration` (5 minutes) since the last price update, add / subtract `spreadBasisPointsIfInactive` (2 BPS - 0.2%) from the price depending on the maximise bool, and this is the price. 4. If It has NEITHER been 1 hr NOR 5 mins since last price update, calculate the BPS diff b/w refPrice and fastPrice (the stale price from `prices[_token]` for the given token, ). 5. If `favorFastPrice(_token)` returns false for this token (i.e., bool to use the fast price or not. Watcher bots can disable fast price for this token due to any suspicion) OR the diff as calculated in prev step exceeds the `maxDeviationBasisPoints` 1000 so 10%, then a spread-based (i.e., higher or lower) price will be returned depending on `_maximise`. If maximise is true, then the greater of `refPrice` and `fastPrice` will be returned. If maxmimise is false, then the lesser of the two is the price. 6. If `favorFastPrice` returns true for the token and the diff in BPS is within the `maxDeviationBasisPoints` threshold, then the price is simply the `fastPrice` which is `prices[token]`. Control now shifts back to `VaultPriceFeed.getPrice()` as the price calculated thus far by `FastPriceFeed.getPrice()` is returned to it. `VaultPriceFeed.getPrice()` takes this price and performs further checks and calculations as shown below: 7. If the token is a stablecoin, check how much its price deviates from 1 USD (10**30). If it the difference b/w 1 USD and its price is within the `maxStrictPriceDeviation` (1e28), continue with this price. 7.1. If the price is more than 1 USD and maximise is true, return that price. Similarly, if the price is less than 1 USD and maximise is false, continue with this price. 7.2 If the price is neither more than 1 USD nor less than it, continue with 1 USD (1e30) as the price. 8. If the token is not a stable coin, add/ subtract (depending on maximise bool) the `spreadBasisPoints` for that token(if any have been set) and continue with this price. 9. If the token has any `adjustmentBps` set, then add/ subtract those from the price calculated thus far, depending on if the `isAdjustmentAdditive[token]` for this token is additive or subtractive. 10. Return the price to the caller.

    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