# Home

Welcome to our docs!

### Website links

1. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade: [gains.trade](https://gains.trade)
2. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade Solana: [sol.gains.trade](https://sol.gains.trade/)
3. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade - Leverage trading: [gains.trade/trading](https://gains.trade/trading)
4. &#x20;<img src="/files/NAte5O6975lUnIxCr0w7" alt="" data-size="line">    gTrade - $GNS staking: [gains.trade/staking](https://gains.trade/staking)
5. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade - gDAI staking: [gains.trade/vault](https://gains.trade/vault)
6. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade - gDAI OTC: [gains.trade/otc](https://gains.trade/otc)
7. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade - Referrals: [gains.trade/referrals](https://gains.trade/referrals)
8. &#x20;<img src="/files/jAhaz5zoS2ZpPquPCDrm" alt="" data-size="line">    gTrade - Polygon <-> Arbitrum bridge: [gains.trade/bridge](https://gains.trade/bridge)
9. &#x20;<img src="/files/wXw7OkXbTZbRMMdcHVbk" alt="" data-size="line">    Gains Network: [gainsnetwork.io](https://gainsnetwork.io)
10. &#x20;<img src="/files/DgJDYEK3zjHRRjOJ56GG" alt="" data-size="line">    Gains Network - GFARM2 bridge and migration: [gainsnetwork.io/bridge](https://gainsnetwork.io/bridge)

### Social medias

1. &#x20; <img src="/files/3G2BGC7Epk5gKxlkNyN6" alt="" data-size="line">    Medium: [gainsnetwork-io.medium.com](https://gainsnetwork-io.medium.com)
2. &#x20;<img src="/files/spzbWC2PgtTMoTSNfNE9" alt="" data-size="line">   Twitter: [twitter.com/GainsNetwork\_io](https://twitter.com/GainsNetwork_io)
3. &#x20; <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">   Telegram: [t.me/GainsNetwork](https://t.me/GainsNetwork)
4. <img src="/files/jW87xPOYo1pIXxzftLHN" alt="" data-size="line"> Discord: [discord.com/invite/gains-network](https://discord.com/invite/gains-network)
5. &#x20; <img src="/files/q3LQi58XhJrws9EWbbGv" alt="" data-size="line">   Reddit: [reddit.com/r/GainsNetwork](https://www.reddit.com/r/GainsNetwork)

### **International Language Channels**

1. <img src="/files/jW87xPOYo1pIXxzftLHN" alt="" data-size="line"> Discord: 🇨🇳🇹🇼 Chinese, 🇯🇵 Japanese, 🇻🇳 Vietnamese
2. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇪🇸🇲🇽 <https://t.me/GNSEspanol>
3. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇨🇳🇹🇼 <https://t.me/GNSChinese>&#x20;
4. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇰🇷 <https://t.me/GNSKorea>&#x20;
5. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇵🇱 <https://t.me/GainsNetworkPoland>
6. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇵🇭 <https://t.me/GNSFilipino>&#x20;
7. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇧🇩 <https://t.me/GNSBangla>
8. <img src="/files/z1DsKotlJ5wr6izuZcCQ" alt="" data-size="line">  🇧🇷🇵🇹 <https://t.me/GNSPortuguese>


# Overview

### Introduction

Gains Network is developing gTrade, a liquidity-efficient, powerful, and user-friendly decentralized leveraged trading platform.

Our uniquely designed synthetic architecture makes gTrade more capital efficient than any existing platform, allows for low trading fees, and a wide range of leverages and pairs: up to 150x on cryptos, 1000x on forex, and 250x on commodities. You can read more about this here: [The gTrade Platform](/gtrade-leveraged-trading/overview).

The protocol revolves around the ecosystem's ERC20 utility token ($GNS). The $GNS token is designed to be actively used within the platform (utility) and to allow ownership of the protocol through revenue capture & governance (soon). It includes $GNS holders receiving platform fees through Single Sided Staking, as well as burning of $GNS using platform revenue. You can read about this here: [GNS Token](/what-is-gains-network/gfarm2-token)

**We do not guarantee price appreciation or depreciation in the future, nor promise any development of the project compared to its current state, and if you buy the token, you do so at your own risk.**

### Long-term vision

1. gTrade becomes the most adopted decentralized leveraged trading platform.
2. Gains Network becomes a DAO governed by the $GNS token (or a derivative like $veGNS).
3. Its only goal is to create great DeFi products that bring revenue that can be distributed in a $GNS staking pool.
4. Development scales horizontally, any team can create governance proposals to receive funding from the governance and create cutting-edge products that bring revenue to $GNS holders.
5. Gains Network launches new products like its own casino and metaverse.

Stay updated by joining our [socials](#follow-the-progress)!

### Team

1. Seb (Founder)
2. Crumbs (Project Lead, Lead dev)
3. Atlas (Project Lead, Product Manager)
4. Konrad (Frontend dev)
5. Ben (Backend dev, Devops, *part-time*)
6. Ves (Marketing, Support, Graphics, Devops, Community)
7. Joseph (Marketing, Project Management, Community)

For the first year of development, our founder worked alone on the project. As the project has grown with further development and marketing, we have been growing the team to achieve our long-term vision as efficiently and rapidly as possible.

### Follow the progress

1. Join and be active in our [Discord](https://discord.com/invite/gains-network) or [Telegram group](https://t.me/GainsNetwork).
2. Read our articles on [Medium](https://medium.com/gains-network).

* News on the [v9.4 update](https://medium.com/gains-network/v9-4-new-innovations-returning-classics-37d3e105dcbf)
* News on the [v9.2 update](https://medium.com/gains-network/v9-2-enhanced-spread-formula-and-competitive-liquidations-9cd99ea3497e)
* News on the [v9.1 update](https://medium.com/gains-network/evolving-gains-network-tokenomics-introducing-buyback-and-distribute-c15ce1fa8fdb)
* News on the [v9 update](https://medium.com/gains-network/v9-elevating-trade-management-19d9cd123f82)
* News on the [v8 update](https://medium.com/gains-network/introducing-gtrade-v8-diamond-refactor-and-smart-contract-integration-a175b96ccb82)
* News on the [v7 update](https://medium.com/gains-network/introducing-gtrade-v7-geth-gusdc-and-multi-collateral-deposits-b4dabcf9b991)
* News on the [v6.4.2 update](https://medium.com/gains-network/price-impact-expiration-v6-4-2-enhancing-altcoin-trading-8d84b039dcce)
* News on the [v6.4 update](https://medium.com/gains-network/gtrade-v6-4-lookbacks-guaranteed-order-execution-and-borrowing-fee-updates-a6fda8fbc4f8)
* News on the [v6.3 gToken Vaults](https://medium.com/gains-network/introducing-gtoken-vaults-ea98f10a49d5)
* News on the [v6.2 update](https://gainsnetwork-io.medium.com/gns-staking-a-new-referral-system-and-much-more-v6-1-1-b6c8166ad210)
* News on the [v6.1 update](https://medium.com/gains-network/gtrade-v6-1-in-depth-b06c0b93fad1)

### **Useful Resources**

* [Arbitrum AMA](https://twitter.com/arbitrum/status/1594747078340915200)
* [Chainlink AMA](https://www.youtube.com/watch?v=bYUS3XYHbZ4)
* [Our community](/), of course!<br>


# GNS Token

The $GNS utility token powers our whole ecosystem.

## GNS: The Utility Token Powering gTrade

<figure><img src="/files/wXOWvRhpSi3XTdH985Gr" alt=""><figcaption><p>GNS token mechanics: how revenue sharing, vault stability, and fee discounts work together within the gTrade ecosystem.</p></figcaption></figure>

### Introduction

$GNS is the backbone of gTrade, enabling efficient liquidity management, revenue distribution, governance, and long-term sustainability. Designed with flexibility in mind, its tokenomics evolve based on community decisions and market conditions. Over time, $GNS has been **net deflationary**, reinforcing its role in the ecosystem.

Originally launched as **$GFARM2** on Ethereum, the token underwent a fair distribution through ETH and LP pools before being migrated to Polygon with a 1:1000 split, rebranding as $GNS. It now operates across multiple chains, supporting gTrade's growth and stability.

### GNS Utility and Tokenomics

$GNS serves multiple core functions within the gTrade ecosystem:

1. **Revenue Sharing** – Trading fees are used for Buybacks & Burns of the token from the open market (BB\&B), with flexibility for direct staking rewards per community alignment.
2. **Counterparty Utility** – Acts as a balancing mechanism for vaults, ensuring liquidity efficiency and protocol stability.
3. **Fee discounts** — $GNS can be staked for fee discounts. In tiers up to 50%. Available here: [$GNS Discounts](https://gains.trade/portfolio/gns-discounts)

#### **How Buyback & Burn (BB\&B) Works**

* **Trading Fees (55%)** – The majority of gTrade’s revenue (from open and close fees in USDC, DAI, WETH) is used to buy back $GNS from the market, reducing supply.
* **Dynamic % of Trader PnL** – Depending on the [gToken Vaults](https://gains-network.gitbook.io/docs-home/liquidity-farming-pools/gtoken-vaults)’ health, a portion of trader losses/profits are used for $GNS buybacks/mints.

BB\&B **creates sustained buy pressure**, followed by **supply reductions** — benefiting all $GNS holders through **organic deflation**. The revenue distribution model can adapt based on governance votes, potentially reintroducing the [**direct staking rewards (SSS)**](https://medium.com/gains-network/gns-single-sided-staking-real-yield-and-decentralization-e66d1089b664) or [**Buyback & Distribute (BB\&D)**](https://medium.com/gains-network/evolving-gains-network-tokenomics-introducing-buyback-and-distribute-c15ce1fa8fdb) model in the future.

Keep track of the GNS burn & supply here ➡️ <https://gains.trade/staking>

* Or this [Dune dashboard](https://dune.com/midgetwhale/gns-burn)

#### **GNS Tokenomics: Adaptive & Deflationary**

$GNS supply mechanics balance protocol needs with long-term sustainability:

* **Minting & Burning** – Vaults dynamically mint and burn $GNS to manage the protocol’s liquidity.
* **Max Supply** – Capped at **100,000,000 $GNS** as a failsafe mechanism (should never be reached under normal conditions).
* **Initial Supply** – **38,892,000 $GNS** at launch, with continued deflation over time.

### How to Get $GNS

$GNS is available on multiple decentralized exchanges (DEXs) and centralized exchanges (CEXs).

#### **DEXs**

* Arbitrum: [Camelot Exchange](https://app.camelot.exchange/pools/0x9b6FF025AeE245D314c09F57B72f0dE6E231c3a6)
* Base: [Uniswap](https://app.uniswap.org/explore/tokens/base/0xfb1aaba03c31ea98a3eec7591808acb1947ee7ac)
* ApeChain: [Camelot Exchange](https://app.camelot.exchange/pools/0x8B2bC7d000D395CBA8442E4d835A5E77e4f9D1FE)

#### **CEXs**

* [Binance](https://www.binance.com/en/trade/GNS_USDT?ref=37754157\&type=spot)

{% embed url="<https://www.youtube.com/watch?v=40B9BVNy6tI>" %}

**We do not guarantee price appreciation or depreciation in the future, nor promise any development of the project compared to its current state, and if you buy the token, you do so at your own risk.**


# Contract Addresses

## Wallet Addresses:

1. Multi-sig (gov fund/treasury): [0xc07EEd650aB255190CA9766162CfB47cFDf72f3a](https://debank.com/profile/0xc07EEd650aB255190CA9766162CfB47cFDf72f3a)
2. Multi-sig ($ARB delegator): [0xF8E93a7D954F7d31D5Fa54Bc0Eb0E384412a158d](https://arbiscan.io/address/0xF8E93a7D954F7d31D5Fa54Bc0Eb0E384412a158d)
3. Multi-sig ($ARB STIP): [0xc5fCA2c19c5Ca269a10e15ee4A800ed82F53787D](https://arbiscan.io/address/0xc5fCA2c19c5Ca269a10e15ee4A800ed82F53787D)
4. Multi-sig (Apechain): [0x34F4911911a0883856E8D15E99fda2d8E0FDBF60](https://apescan.io/address/0x34F4911911a0883856E8D15E99fda2d8E0FDBF60)

## Active Contracts:

1. [Apechain Mainnet](/what-is-gains-network/contract-addresses/apechain-mainnet)
2. [Arbitrum Mainnet](/what-is-gains-network/contract-addresses/arbitrum-mainnet)
3. [Base Mainnet](/what-is-gains-network/contract-addresses/base-mainnet)
4. [MegaETH Mainnet](/what-is-gains-network/contract-addresses/megaeth-mainnet)
5. [Polygon Mainnet](/what-is-gains-network/contract-addresses/polygon-mainnet)

## Old Contracts:

Old contracts can still interact with the ecosystem but are not necessary or advisable to use. They mainly exist to allow anyone who still holds GFARM2 or NFTs to migrate.\
\
\- Old NFTs can still be swapped to bridgeable NFTs and bridged [here](https://gainsnetwork.io/bridge/), and redeemed for GNS [here](https://gains.trade/nft-redemption).\
\- Old GFARM2 tokens can still be bridged and converted to $GNS [here](https://gainsnetwork.io/bridge/).

### Polygon:

1. GFARM2 Token: [0x7075cAB6bCCA06613e2d071bd918D1a0241379E2](https://polygonscan.com/address/0x7075cAB6bCCA06613e2d071bd918D1a0241379E2/transactions)
2. GFARM2 NFT 1: [0xF9A4c522E327935BD1F5a338c121E14e4cc1f898](https://polygonscan.com/address/0xF9A4c522E327935BD1F5a338c121E14e4cc1f898)
3. GFARM2 NFT 2: [0x77cd42B925e1A82f41d852D6BE727CFc88fddBbC](https://polygonscan.com/address/0x77cd42B925e1A82f41d852D6BE727CFc88fddBbC/transactions)
4. GFARM2 NFT 3: [0x3378AD81D09DE23725Ee9B9270635c97Ed601921](https://polygonscan.com/address/0x3378AD81D09DE23725Ee9B9270635c97Ed601921/transactions)
5. GFARM2 NFT 4: [0x02e2c5825C1a3b69C0417706DbE1327C2Af3e6C2](https://polygonscan.com/address/0x02e2c5825C1a3b69C0417706DbE1327C2Af3e6C2/transactions)
6. GFARM2 NFT 5: [0x2D266A94469d05C9e06D52A4D0d9C23b157767c2](https://polygonscan.com/address/0x2D266A94469d05C9e06D52A4D0d9C23b157767c2/transactions)
7. GFARM2 -> GNS migration: [0xd285f881886505b9Ef6684E1aaa7949a56B0C7Da](https://polygonscan.com/address/0xd285f881886505b9ef6684e1aaa7949a56b0c7da)
8. NFTs -> GNS redemption: [0xC7d91A130ad0521E212f04c2CFA2aDAf926df6AE](https://polygonscan.com/address/0xC7d91A130ad0521E212f04c2CFA2aDAf926df6AE)

### Arbitrum:

1. GainsNetworkNft1: [0x75cbcc5414C539C2B302A5fA60E30B949D2D6F89](https://arbiscan.io/address/0x75cbcc5414C539C2B302A5fA60E30B949D2D6F89)
2. GainsNetworkNft2: [0xD1F024ba4Dbb1593B486cB5031b3AC5aC28e8A4e ](https://arbiscan.io/address/0xD1F024ba4Dbb1593B486cB5031b3AC5aC28e8A4e)
3. GainsNetworkNft3: [0x9834159EAF9811cf4C568294D5C7C9158F84b384 ](https://arbiscan.io/address/0x9834159EAF9811cf4C568294D5C7C9158F84b384)
4. GainsNetworkNft4: [0x40F0AeaB6383Be2f254cE40B79089070Fa1a21A1 ](https://arbiscan.io/address/0x40F0AeaB6383Be2f254cE40B79089070Fa1a21A1)
5. GainsNetworkNft5: [0x5e3b541Ad6AcC4381C110247946C863e05ffc9BE](https://arbiscan.io/address/0x5e3b541Ad6AcC4381C110247946C863e05ffc9BE)
6. NFTs -> GNS redemption: [0x30d8C505516Ab7693e2DE491bdceB028d8ae7EbF](https://arbiscan.io/address/0x30d8C505516Ab7693e2DE491bdceB028d8ae7EbF)

### Ethereum:

1. GFARM2 Token: [0x831091da075665168e01898c6dac004a867f1e1b](https://etherscan.io/token/0x831091da075665168e01898c6dac004a867f1e1b)
2. GFARM2 NFTs: [0x43ccd9ea8f64b8918267f7ee4a071d3e9168f9cd](https://etherscan.io/token/0x43ccd9ea8f64b8918267f7ee4a071d3e9168f9cd)
3. GFARM2 Bridgeable NFT 1: [0x2Ac9E0171838877f3f37cDD7076B83523A29414](https://etherscan.io/token/0x2Ac9E0171838877f3f37cDD7076B83523A294140)
4. GFARM2 Bridgeable NFT 2: [0x580d1938074D48C34F2e2D1371af0Bf02Ac44701](https://etherscan.io/token/0x580d1938074D48C34F2e2D1371af0Bf02Ac44701)
5. GFARM2 Bridgeable NFT 3: [0xa443693255966f83E9Ae6C6132858cCdF2F3CA50](https://etherscan.io/token/0xa443693255966f83E9Ae6C6132858cCdF2F3CA50)
6. GFARM2 Bridgeable NFT 4: [0xe5fa95e5B505452680072600f5A751010aBe4377](https://etherscan.io/token/0xe5fa95e5B505452680072600f5A751010aBe4377)
7. GFARM2 Bridgeable NFT 5: [0xAE3bC89bC71CA243A275A06ba0708cD166d31155](https://etherscan.io/token/0xAE3bC89bC71CA243A275A06ba0708cD166d31155)
8. Bridgeable NFT Swap: [0x14e2f9B0381Af4227D26BEE7d8E4D424466A7F3F](https://etherscan.io/address/0x14e2f9B0381Af4227D26BEE7d8E4D424466A7F3F)


# Apechain Mainnet

**Tokens:**

1. $GNS Token: [0xe31C676d8235437597581b44c1c4f8A30e90b38a](https://apescan.io/address/0xe31C676d8235437597581b44c1c4f8A30e90b38a)

**Bridges:**

1. ERC20 Bridge: [0xa16e00C26786B9861b3e105296197eA0f891c879](https://apescan.io/address/0xa16e00C26786B9861b3e105296197eA0f891c879)

**Admin contracts:**

1. ProxyAdmin: [0xD65bE79FA0634656657df160267Fa440ac13dA9d](https://apescan.io/address/0xd65be79fa0634656657df160267fa440ac13da9d)
2. GNSTimelockOwner (14-day): [0x164bb61951a6c628A69e4B5af10e9C691221526D](https://apescan.io/address/0x164bb61951a6c628A69e4B5af10e9C691221526D)
3. GNSTimelockManager (3-day): [0x190fF92E176Bf8Db2A494cf6f25451a7E259fb16](https://apescan.io/address/0x190fF92E176Bf8Db2A494cf6f25451a7E259fb16)

**Core Contracts:**

1. GNSMultiCollatDiamond: [0x2BE5D7058AdBa14Bc38E4A83E94A81f7491b0163](https://louper.dev/diamond/0x2BE5D7058AdBa14Bc38E4A83E94A81f7491b0163?network=apeChain)
2. GNSStaking: [0x6dCD75474F9BDE2793cb3Da00b8959fb27BFa9d5](https://apescan.io/address/0x6dCD75474F9BDE2793cb3Da00b8959fb27BFa9d5)

**APE Collateral Contracts:**

1. gAPE: [0xDd9C98e5022AF88B9c991ab24F02B4A8Be81D860](https://apescan.io/address/0xDd9C98e5022AF88B9c991ab24F02B4A8Be81D860)
2. gAPEOpenPnlFeed: [0x33FE6f374C4a44C50F4362c93372f0EB09d968F5](https://apescan.io/address/0x33FE6f374C4a44C50F4362c93372f0EB09d968F5)


# Arbitrum Mainnet

**Tokens:**

1. $GNS Token: [0x18c11FD286C5EC11c3b683Caa813B77f5163A122](https://arbiscan.io/address/0x18c11FD286C5EC11c3b683Caa813B77f5163A122)

**Bridges:**

1. ERC20 Bridge: [0x01cAaaA682Ceba8cd6c02f93BB1393fB415fA5e2](https://arbiscan.io/address/0x01cAaaA682Ceba8cd6c02f93BB1393fB415fA5e2)
2. ERC721 (Minting) Bridge: [0x0F9E4375facBeB90DAA850f677819b438ce50827](https://arbiscan.io/address/0x0F9E4375facBeB90DAA850f677819b438ce50827)

**Admin contracts:**

1. ProxyAdmin: [0xe18be0113c38c91b3B429d04fDeb84359fBCb2eB](https://arbiscan.io/address/0xe18be0113c38c91b3B429d04fDeb84359fBCb2eB)
2. GNSTimelockOwner (14-day): [0x5f5E4892BAB94d94DC57a3edeA3c138167c4DF0F ](https://arbiscan.io/address/0x5f5E4892BAB94d94DC57a3edeA3c138167c4DF0F)
3. GNSTimelockManager (3-day): [0x1632C38cB208df8409753729dBfbA5c58626F637](https://arbiscan.io/address/0x1632C38cB208df8409753729dBfbA5c58626F637)

**Core Contracts:**

1. GNSMultiCollatDiamond: [0xFF162c694eAA571f685030649814282eA457f169](https://louper.dev/diamond/0xFF162c694eAA571f685030649814282eA457f169?network=arbitrum)
2. GNSStaking: [0x7edDE7e5900633F698EaB0Dbc97DE640fC5dC015](https://arbiscan.io/address/0x7edDE7e5900633F698EaB0Dbc97DE640fC5dC015)

**GNS Collateral Contracts:**

1. gGNS: [0x4BeeF1113F968326905224D2Ca272f3032A9a9F4](https://arbiscan.io/address/0x4BeeF1113F968326905224D2Ca272f3032A9a9F4)
2. gGNS OpenPnlFeed: [0x4ca1638754be8060e544aca4a4f43702be30e0d1](https://arbiscan.io/address/0x4ca1638754be8060e544aca4a4f43702be30e0d1)

**DAI Collateral Contracts:**

1. gDAI: [0xd85E038593d7A098614721EaE955EC2022B9B91B ](https://arbiscan.io/address/0xd85E038593d7A098614721EaE955EC2022B9B91B)
2. gDAI OpenPnlFeed: [0x990BA9Edd8a9615A23E4c452E63A80e519A4a23D ](https://arbiscan.io/address/0x990BA9Edd8a9615A23E4c452E63A80e519A4a23D)

**WETH Collateral Contracts:**

1. gETH: [0x5977A9682D7AF81D347CFc338c61692163a2784C](https://arbiscan.io/address/0x5977A9682D7AF81D347CFc338c61692163a2784C)
2. gETH OpenPnlFeed: [0x018D9A3F0D06cCb7C305B7C9219a4307e1f9f27e](https://arbiscan.io/address/0x018D9A3F0D06cCb7C305B7C9219a4307e1f9f27e)

**USDC Collateral Contracts:**

1. gUSDC: [0xd3443ee1e91aF28e5FB858Fbd0D72A63bA8046E0](https://arbiscan.io/address/0xd3443ee1e91aF28e5FB858Fbd0D72A63bA8046E0)
2. gUSDC OpenPnlFeed: [0xBF55C78132ab06a2B217040b7A7F20B5cBD47982](https://arbiscan.io/address/0xBF55C78132ab06a2B217040b7A7F20B5cBD47982)


# Base Mainnet

**Tokens:**

1. $GNS Token: [0xFB1Aaba03c31EA98A3eEC7591808AcB1947ee7Ac](https://basescan.org/address/0xFB1Aaba03c31EA98A3eEC7591808AcB1947ee7Ac)

**Bridges:**

1. ERC20 Bridge: [0x1671e2265CbBB3f13dFbbf76661cBc19d82143a9](https://basescan.org/address/0x1671e2265cbbb3f13dfbbf76661cbc19d82143a9)

**Admin contracts:**

1. ProxyAdmin: [0xD65bE79FA0634656657df160267Fa440ac13dA9d](https://basescan.org/address/0xD65bE79FA0634656657df160267Fa440ac13dA9d)
2. GNSTimelockOwner (14-day): [0x3A00b1Fa6cb7D07043Fc2B2066066735f9419E7A](https://basescan.org/address/0x3A00b1Fa6cb7D07043Fc2B2066066735f9419E7A)
3. GNSTimelockManager (3-day): [0x03908e9aeBA0a23c1c476F946B99B6E9ea0B8f08](https://basescan.org/address/0x03908e9aeBA0a23c1c476F946B99B6E9ea0B8f08)

**Core Contracts:**

1. GNSMultiCollatDiamond: [0x6cD5aC19a07518A8092eEFfDA4f1174C72704eeb](https://louper.dev/diamond/0x6cD5aC19a07518A8092eEFfDA4f1174C72704eeb?network=base)
2. GNSStaking: [0x28efAa11199DAF45AA8fBf95f920e5bc090DCbF3](https://basescan.org/address/0x28efAa11199DAF45AA8fBf95f920e5bc090DCbF3)

**USDC Collateral Contracts:**

1. gUSDC: [0xad20523A7dC37bAbc1CC74897E4977232b3D02e5](https://basescan.org/address/0xad20523A7dC37bAbc1CC74897E4977232b3D02e5)
2. gUSDC OpenPnlFeed: [0xefA1C2753daD877Bb6531bBa9D9c589B5433Be37](https://basescan.org/address/0xefA1C2753daD877Bb6531bBa9D9c589B5433Be37)
3. gUSDC LockedDepositNft: [0x7d0131AceEfd2ACc919d7B2AC32e8e6C81a05cEB](https://basescan.org/address/0x7d0131aceefd2acc919d7b2ac32e8e6c81a05ceb)

**BtcUSD Collateral Contracts:**

1. gBTCUSD: [0xB7Cb7cB7C3cD96e251c9bF8800B9631134BbAdc6](https://basescan.org/address/0xB7Cb7cB7C3cD96e251c9bF8800B9631134BbAdc6)
2. gBTCUSD OpenPnlFeed: [0xcEc10C66d711250db67945254F79628457365CC8](https://basescan.org/address/0xcEc10C66d711250db67945254F79628457365CC8)


# MegaETH Mainnet

**Tokens:**

1. $GNS Token: [0x551DFe38994eC53c9E7E18084D73893225Eea3bf](https://mega.etherscan.io/address/0x551DFe38994eC53c9E7E18084D73893225Eea3bf)

**Bridges:**

1. ERC20 Bridge: [0xEB24C00442Fd95d18AC8F62d498BEF5e167e1a54](https://mega.etherscan.io/address/0xEB24C00442Fd95d18AC8F62d498BEF5e167e1a54)

**Admin contracts:**

1. ProxyAdmin: [0x261292B273c918982820E30e9F24bfA41484296f](https://mega.etherscan.io/address/0x261292B273c918982820E30e9F24bfA41484296f)
2. GNSTimelockOwner (14-day): [0xc38964AF46708156A373295612faBDC3687A5D11](https://mega.etherscan.io/address/0xc38964AF46708156A373295612faBDC3687A5D11)
3. GNSTimelockManager (3-day): [0x93FBA1B058f07173095ce109379ed00669474Acf](https://mega.etherscan.io/address/0x93FBA1B058f07173095ce109379ed00669474Acf)

**Core Contracts:**

1. GNSMultiCollatDiamond: [0x2D5B1ba6E2093a5b927Fe5bF8C049B107de31eaF](https://mega.etherscan.io/address/0x2D5B1ba6E2093a5b927Fe5bF8C049B107de31eaF)
2. GNSStaking: [0x4F1D70A563c2cA96b076cc28E84Ec25da8D6f486](https://mega.etherscan.io/address/0x4F1D70A563c2cA96b076cc28E84Ec25da8D6f486)

**USDm Collateral Contracts:**

1. gUSDm: [0x46344456f130e9dcdeA7F98cDb0E02fB9F4ab72D](https://mega.etherscan.io/address/0x46344456f130e9dcdeA7F98cDb0E02fB9F4ab72D)
2. gUSDm OpenPnlFeed: [0x637025a9F5e2380E3BBe744Ed4Ffb3191cf5EF4D](https://mega.etherscan.io/address/0x637025a9F5e2380E3BBe744Ed4Ffb3191cf5EF4D)
3. gUSDm LockedDepositNft: [0x1d0EfF8Bcfa6A10334a5caeCa846c95d32Cc5ba1](https://mega.etherscan.io/address/0x1d0EfF8Bcfa6A10334a5caeCa846c95d32Cc5ba1)&#x20;


# Polygon Mainnet

**Tokens:**

1. GNS Token: [0xE5417Af564e4bFDA1c483642db72007871397896](https://polygonscan.com/token/0xE5417Af564e4bFDA1c483642db72007871397896)

**Bridges:**

1. ERC20 Bridge: [0xDF774A4F3EA5095535f5B8f5b9149caF90FF75Bd](https://polygonscan.com/address/0xDF774A4F3EA5095535f5B8f5b9149caF90FF75Bd)
2. ERC721 (Locking) Bridge: [0xa33f7069f075A54481868e4C0b8D26925A218362](https://polygonscan.com/address/0xa33f7069f075A54481868e4C0b8D26925A218362)

**Admin contracts:**

1. ProxyAdmin: [0xdbCd002f96F62781BBe65FBe24f4d6265d416BaD](https://polygonscan.com/address/0xdbCd002f96F62781BBe65FBe24f4d6265d416BaD)
2. GNSTimelockOwner (14-day): [0x322e18FdB5d0B0221E4724dcC5883c4B7896dA0E](https://polygonscan.com/address/0x322e18FdB5d0B0221E4724dcC5883c4B7896dA0E)
3. GNSTimelockManager (3-day): [0xf0A8531505F96B8deCce7857CA3AB57490f44A40](https://polygonscan.com/address/0xf0A8531505F96B8deCce7857CA3AB57490f44A40)

**Global Contracts:**

1. GNSMultiCollatDiamond: [0x209A9A01980377916851af2cA075C2b170452018](https://louper.dev/diamond/0x209A9A01980377916851af2cA075C2b170452018?network=polygon)
2. GNSStaking: [0x8C74B2256fFb6705F14aDA8E86FBd654e0e2BECa](https://polygonscan.com/address/0x8C74B2256fFb6705F14aDA8E86FBd654e0e2BECa)

**DAI Collateral Contracts:**

1. gDAI: [0x91993f2101cc758D0dEB7279d41e880F7dEFe827](https://polygonscan.com/address/0x91993f2101cc758D0dEB7279d41e880F7dEFe827)
2. gDAI OpenPnlFeed: [0x8d687276543b92819F2f2B5C3faad4AD27F4440c](https://polygonscan.com/address/0x8d687276543b92819F2f2B5C3faad4AD27F4440c)

**WETH Collateral Contracts:**

1. gETH: [0x1544E1fF1a6f6Bdbfb901622C12bb352a43464Fb](https://polygonscan.com/address/0x1544E1fF1a6f6Bdbfb901622C12bb352a43464Fb)
2. gETH OpenPnlFeed: [0xF07f4507DD6A057Aea509cB9b218B7C4D1894473](https://polygonscan.com/address/0xF07f4507DD6A057Aea509cB9b218B7C4D1894473)

**USDC Collateral Contracts:**

1. gUSDC: [0x29019Fe2e72E8d4D2118E8D0318BeF389ffe2C81](https://polygonscan.com/address/0x29019Fe2e72E8d4D2118E8D0318BeF389ffe2C81)
2. gUSDC OpenPnlFeed: [0xFF84e736A15F80E7E104e153d7f7D6c9bd6fE822](https://polygonscan.com/address/0xFF84e736A15F80E7E104e153d7f7D6c9bd6fE822)


# Overview

Learn everything about gTrade, the liquidity-efficient decentralized leveraged trading platform.

<figure><img src="/files/dr474CukcMUCyAZ1a0Pu" alt=""><figcaption><p>Start trading at gains.trade</p></figcaption></figure>

## Summary

### Trading experience:

1. **Full custody of your funds**\
   -> no deposit or signup
2. **Median spot prices**\
   -> no scamwicks
3. **Zero price impact on BTC and ETH**
4. **Crypto, forex, and commodities available**
5. **High leverages available**\
   -> up to 150x on cryptos, 1000x on forex, 250x on commodities
6. **Competitive fees**
7. **Transparent & decentralized**\
   -> 100% on-chain execution of trades
8. **Top-notch user experience**\
   -> interface evolved with more than 4 years of user feedback

### Trading engine:

1. **No order books or liquidity for each pair**\
   -> gToken vaults for all trading pairs listed.\
   -> 100x+ more capital efficient.
2. **Synthetic leverage (not borrowed)**\
   -> up to 100x+ more capital efficient (depending on leverage used).
3. **Real-time custom Chainlink decentralized oracle network (DON)**\
   -> real-time spot prices on-demand, on-chain.\
   -> first oracle network of this kind on mainnet ever.

## How does it work?

Trades are opened with $USDC, $DAI, $GNS, $WETH, or $APE collateral, regardless of the trading pair. The leverage is synthetic and backed by [the respective gToken vault](/liquidity-farming-pools/gtoken-vaults), and the $GNS token. Trader profit is taken from the vaults to pay the traders PnL (if positive), or receives trader losses from trades if their PnL was negative.

### Powered by Chainlink

While all derivatives platforms generate their own prices through order books or similar models, which often ends up in prices that do not correspond to the real spot price of the asset, we use a custom real-time [Chainlink](https://chain.link/) node operators network to get the median price for each trading order.&#x20;

A detailed explanation of how the DON (decentralized oracle network) works is available [here](https://gainsnetwork-io.medium.com/gains-farm-using-chainlink-to-power-decentralized-leveraged-trading-fe954b37eb97).

### Most accurate

The DON effectively filters out any outlier price action happening on a single exchange, whether done through manipulation purposes or simply from a lack of liquidity, allowing traders to rest at ease since they don't be liquidated because of a scamwick, for example.

It is worth noting that these are **your** trades. **We cannot open, close, or edit any aspect of your open trades** unless you have approved the smart contract to allow this by setting a stop loss or take profit, or if you are in a position which necessitates liquidation.&#x20;

Please note that there is a function available to governance to pause the opening of new trades which is used when a contract is upgraded  - but this would not close any traders open positions, **all traders still retain control** on closing their trades.

Finally, the trading engine is **fully decentralized** and users **keep custody of the funds**. We do not require any sign up or deposit to start trading.

### Concrete example

As the gTrade architecture uses multiple price sources for every pair, the ETH/USD price only dipped down to $**2,980.32** on a specific volatile movement.

Lets take a look at the price action on one of the best known centralized exchanges.

![](/files/9cYTVNLIURL8ajlIqff0)

**$2,977.62** was the botto&#x6D;**.** This means one of your trades could have been **liquidated** on this exchange because it would have reached below your liquidation threshold, and your trade would **not have remained open to later see profit**.

The price difference between the Chainlink DON and the centralized exchange price is 0.09% in this case, which represents **13.5% PnL** on 150x leverage. This example is an average one, as it often happens multiple times a week, and it is clearly **enough to make a trading strategy unprofitable**. There is also generally a bigger one once a month with sometimes 1% or more of difference compared to our fair median feed.

Not only that - but if you look at the liquidity, selling your position would've taken the price down further, which would have contributed to the so-called "scamwick" on this exchange.

### Exceptional user experience

![Start trading at gains.trade](/files/4gguivKN0EQWsyo0AIPZ)

Due to the high liquidity efficiency of using a single liquidity pool per gToken vault for all orders executed on all pairs listed, we are able to offer the **widest trading pairs and leverages offering**.

We have also been improving the interface and listening to users' feedback for more than 3 years.

### Competitive trading fees

The fees are distributed to the governance fund, gToken liquidity providers, $GNS staking, referrals, and to the network of oracle bots executing the limit orders in a decentralized manner.

You can read more about our fees [here](/gtrade-leveraged-trading/fees-and-spread).

### Liquidity efficiency

Since all trades use gToken liquidity layers (trading vault), we have a big advantage over other platforms who have to build new liquidity in their order books every time they list a new pair, and maintain high liquidity on each pair.

By building big gToken vaults (with trading fees incentives), every trading pair listed on our platform benefits from bigger position sizes. This means the platform only requires $USDC, $DAI, $GNS, $WETH, or $APE liquidity for **ALL** pairs that can be traded on the platform.&#x20;

This is only possible because our architecture doesn't match buying/selling orders using an order book, and because the leverage of trades is "virtual". The PnL is calculated in our smart contracts and settled against the gToken vaults.

### Current limitations

1. Maximum open interest (long/short) per pair and per group of correlated pairs.\
   -> risk management for liquidity providers.


# Incentives

{% hint style="info" %}
Please note that STIP-Bridge is no longer active.
{% endhint %}

Gains Network is part of the Arbitrum STIP-Bridge program, offering incentives through September 2024. Incentives target high value network participants: traders and liquidity providers of $GNS as well as $gDAI, $gUSDC.&#x20;

**Amount:**&#x20;

2.25M $ARB total (1.8M for traders, 337.5k for LPs, 112.5k for GCGP-Bridge)

***

**Duration:**&#x20;

June 28, 2024 00:00 UTC  ->  September 13, 2024 00:00 UTC

***

**Reward distribution:**&#x20;

Weekly for traders; on-going for LPs


# Trading Incentives

## Please note that STIP-Bridge incentives are no longer active, and the information below refers to the last active epoch.

### Any unclaimed rewards can be claimed at <https://gains.trade/portfolio/rewards>

###

***

## Last epoch (Epoch 12)

{% hint style="info" %}
Please note that only altcoins (All cryptocurrencies besides *BTC/USD* and *ETH/USD*) count toward rewards for this epoch!
{% endhint %}

**Fees:** 70% (57,272 $ARB)

**PnL:** 20% (16,364 $ARB)

**Loyalty:** 10% (81,82 $ARB)

### Overview <a href="#overview" id="overview"></a>

163,636 $ARB (1.8m $ARB in total) is being distributed weekly to traders based on their performance among 4 categories: **fees, PnL, PnL (%), loyalty**.

These were identified as a balanced set of categories that reward positive behaviors for the protocol (fees & loyalty) and the trader (PnL & PnL (%)), encouraging growth and retention.

The final reward amount can be claimed on-chain shortly after the end of each weekly epoch at: <https://gains.trade/portfolio/rewards>

Below is a breakdown of each category:

**Fees**

The fee category incentives are distributed weekly based on open & close fee spending. Traders are rewarded a portion of the rewards based on their share of fees spent. The higher the fee share, the larger the reward.

`Trader rewards = traderWeeklyFees / protocolWeeklyFees * weeklyFeesIncentives`

Example: The weekly fee incentives are 139,091 $ARB. Trader A pays $500 in fees throughout the week. The protocol earned $250k fees in total. Trader A will receive **500 / 250000 \* 139091 = 278.2 $ARB**

*\*Fee category rewards are capped at 75% of the total amount of fees earned by the protocol. Market value of $ARB rewards is determined at time of weekly snapshot. So if `weeklyFeesIncentives * ARB/USD > total fees * 0.75`, the distribution will be reduced accordingly.*

*\*\*Borrowing fee is not included, only action based open & close fees*

**PnL**

The PnL category incentives are distributed weekly based on PnL. Traders are rewarded a portion of the rewards based on their weekly profits. The higher the profit share, the larger the reward. If a trader PnL is negative for the week, it is treated as 0. The protocol weekly PnL is then the sum of all profitable traders, it is not the true PnL (since unprofitable traders PnL is treated as 0).

`Trader rewards = max(0, traderWeeklyPnl) / totalProtocolPositivePnl * weeklyPnLIncentives`

Example: The weekly PnL incentives are 16,363 $ARB. Trader A profits $5k in pnL throughout the week. The total protocol positive PnL was $250k. Trader A will receive **5000 / 250000 \* 16363 = 327.3 $ARB**

#### **PnL (%)** <a href="#pnl-1" id="pnl-1"></a>

The PnL (%) category incentives are distributed weekly based on PnL (%). Traders are rewarded a portion of the rewards based on their weekly PnL percentage. The higher their relative PnL share, the larger the reward. If a trader PnL (%) is negative for the week, it is treated as 0. The protocol weekly PnL (%) is then the sum of all traders with positive percentages.

`Trader rewards = max(0, traderWeeklyPnlP) / totalProtocolPnlP * weeklyPnLPercentageIncentives`

Example: The weekly PnL (%) incentives are 8,182 $ARB. Trader A relative PnL is 400% throughout the week. The total protocol positive PnL (%) was 12,000%. Trader A will receive **400 / 12000 \* 8182 = 272.7 $ARB**

#### **Loyalty** <a href="#loyalty-points" id="loyalty-points"></a>

The loyalty incentives are distributed weekly based on trading frequency. Each day a trader trades, they earn points towards the weekly distribution. The more fees spent in a day, the more points earned.

| Fees              | Points |
| ----------------- | ------ |
| Min Fee paid $8   | 1      |
| Min Fee paid $40  | 5      |
| Min Fee paid $200 | 25     |
| Min Fee paid $400 | 50     |

`Trader rewards = traderWeeklyLoyaltyPoints / totalWeeklyProtocolLoyaltyPoints * weeklyLoyaltyIncentives`

Example: The weekly loyalty incentives are 8,182 $ARB. Trader A trades 6 days, 5 of which qualify for points, totaling 105 points throughout the week. The total protocol loyalty points was 12,754. Trader A will receive **105 / 12754 \* 8182 = 67.4 $ARB**

*Daily breakdown:*

| Day       | Fees Spent | Points  | Protocol points |
| --------- | ---------- | ------- | --------------- |
| 1         | 0          | 0       | 1025            |
| 2         | 225        | 25      | 1275            |
| 3         | 59         | 5       | 2400            |
| 4         | 380        | 25      | 2100            |
| 5         | 5          | 0       | 1843            |
| 6         | 612        | 50      | 900             |
| 7         | 0          | 0       | 3211            |
| **Total** | ​          | **105** | **12754**       |

​


# Tech Overview & Resources

Reward system is fully auditable

## Overview

Three systems make up the Arbitrum STIP rewards program: 1. Stats; 2. Points; and 3. Rewards.

***tl;dr: stats => points => rewards***

## Stats Subgraph

Gains Network has published a subgraph to track stats & points from on-chain trading events. Both the data and code are public:

***Arbitrum Subgraph*****:** <https://thegraph.com/hosted-service/subgraph/gainsnetwork-org/gtrade-stats-arbitrum>

***GitHub*****:** <https://github.com/GainsNetwork-org/gtrade-stats-subgraph/tree/main/packages/stats-subgraph>

## Graph Client

Gains Network has published a client library to NPM to both interact with raw stats & points, as well as access all rewards data. Rewards are not tracked on the subgraph and instead are computed in real-time through the use of client-side queries. Both the client library and code are public:

***NPM Library*****:** <https://www.npmjs.com/package/@gainsnetwork/graph-client>

***GitHub*****:** <https://github.com/GainsNetwork-org/gtrade-stats-subgraph/tree/main/packages/graph-client>

## Claims Contract

Gains Network has deployed a contract for claiming $ARB rewards. The contract is verified on Arbiscan.&#x20;

***Contract:*** <https://arbiscan.io/address/0x6ac331B603373D0006D72d3a3159B4C35e1006e8#code>

The contract stores a Merkle root and IPFS CID per epoch. The root is used to distribute rewards, and the CID is for data transparency, allowing the community to verify the rewards data independently.

## Weekly Job

Each week a job runs that:

1\. Computes rewards using the graph-client

2\. Generates a Merkle tree&#x20;

3\. Publishes tree to IPFS&#x20;

4\. Submits root & CID to contract

This job is not open source but its output can be fully verified.

## Verification

Each module of the system can be independently verified.

* Trading stats -- code & index can be compared against blockchain events independently&#x20;
* Trading points -- conversion from stats to points can be compared against blockchain events independently&#x20;
* Trading rewards -- graph-client allows anyone to compute rewards for any epoch at any time. This can be compared against the CID and Merkle root on-chain.


# LP Incentives

Here you can find currently incentivized liquidity pools

<details>

<summary><img src="/files/GlOdfLnY9lDwjEtkIuMm" alt="" data-size="line"> Base</summary>

\
**Timeswap**\
[gUSDC/USDC, lend](https://app.timeswap.io/lend/a4c3c89a-fee2-44c8-9600-1074da400652)\
[gUSDC/USDC, borrow](https://app.timeswap.io/borrow/a4c3c89a-fee2-44c8-9600-1074da400652)\
\
**Maverick**\
[USDC-gUSDC boosted position](https://app.mav.xyz/boosted-position/0x27fFd5a3828275c5938b9bE7a8db44b7DB897A34/0xB2E6E155f3c6A12FB0708B75224c50d6aE2b03FC?chain=8453\&f=true)

</details>

<details>

<summary><img src="/files/JKz97fe9YkdM2asAqhrq" alt="" data-size="line"> Arbitrum</summary>

\
**Pendle**\
[gDAI LP pool](https://app.pendle.finance/trade/pools/0xa9104b8b6698979568852c30231871e28a482b3c/zap/in?chain=arbitrum)\
[gUSDC LP pool](https://app.pendle.finance/trade/pools/0xa877a0e177b54a37066c1786f91a1dab68f094af/zap/in?chain=arbitrum)\
\
**Penpie**\
[Pendle gDAI LP boosted staking](https://www.pendle.magpiexyz.io/stake/0xA9104b8B6698979568852C30231871e28A482b3C)\
\
**Camelot**\
[GNS-ETH v3](https://app.camelot.exchange/pools/0x9b6FF025AeE245D314c09F57B72f0dE6E231c3a6)\
[GNS-USDC v3](https://app.camelot.exchange/pools/0x1f3572BaeE36360D23E976c244E08160523Ce7eB)\
[gUSDC-USDC v3](https://app.camelot.exchange/pools/0x1470b62eB67225f6EcDF8249293C8052f1cd2717)\
\
**Timeswap**\
[gUSDC/USDC, lend](https://app.timeswap.io/lend/a4c3c89a-fee2-44c8-9600-1074da400652)\
[gUSDC/USDC, borrow](https://app.timeswap.io/borrow/a4c3c89a-fee2-44c8-9600-1074da400652)\
\
**Maverick**\
[USDC-gUSDC boosted position](https://app.mav.xyz/boosted-position/0x4830c06cb23bB787A4f1925d26aEc9E4b828Bb37/0x57C57352f9D5e1679bB9D7c969679204478CE3f5?chain=42161\&f=true)\
\
**Silo**\
[GNS, ETH, USDC.e market](https://app.silo.finance/silo/0xfc6778a6955e1ceCAc448051de967f9b5Ff4D647)<br>

</details>

<details>

<summary><img src="/files/VmhXApkWSotuDj8Q7n6N" alt="" data-size="line"> Polygon</summary>

\
**Quickswap**\
[GNS/wPOL v3](https://quickswap.exchange/#/swap?inputCurrency=0xe5417af564e4bfda1c483642db72007871397896\&outputCurrency=0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270\&swapIndex=0)

</details>


# Setting up to trade

This guide covers setting up Metamask to trade, getting funds to trade with, and RPC Endpoints.

To trade, you will need to connect to one of the networks which gTrade is deployed on.

The guides for setting up on each network gTrade is available on are here:

* [Polygon Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/polygon-network-setup)
  * Lowest gas costs
  * Supports lower position sizes
  * Requires 2 block confirmation (4 seconds)
  * Occasional reorgs
* [Arbitrum Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/arbitrum-network-setup)
  * No block confirmations required
  * Fastest transactions
  * Slightly higher transaction cost
  * Higher minimum position size required

###


# Polygon Network Setup

### Polygon Metamask Setup

To add Polygon automatically to metamask go to [Polygonscan](https://polygonscan.com/) and scroll to the bottom. Then on click "Add Network":<br>

<figure><img src="/files/3I6nn4rsFMfqisbyNR0z" alt=""><figcaption><p>Scroll to the bottom of the page to see the button.</p></figcaption></figure>

To add it manually, see the [Polygon documentation on set up](https://wiki.polygon.technology/docs/develop/metamask/config-polygon-on-metamask/).

See below for more information on RPC endpoints.

After following each step you can now switch between the Ethereum and Polygon (MATIC) networks in Metamask as you want.

### Getting Funds to Polygon

Polygon uses the native token MATIC to pay for transactions, including to manage trades on gTrade. If you don't have any MATIC tokens yet, you can claim a small amount of MATIC for free on [matic.supply](https://matic.supply/).&#x20;

You can then convert other assets to MATIC on Quickswap to have more MATIC for transactions.

If you don't have any other assets on Polygon, there are a number of ways to move them there.&#x20;

1. Bridge funds from Ethereum using the [Polygon Bridge](https://wallet.polygon.technology/).\
   This takes about 10 minutes.
2. Bridge funds using another bridging solution.
3. Most centralised exchanges support withdrawing MATIC to Polygon. \
   Ensure you have selected Polygon as the chain to withdraw to and not Ethereum.

### RPC Endpoints

RPCs are what Metamask uses to connect to the blockchain, whether to fetch information or to send transactions.

Public RPCs are the easiest way to access the MATIC network. During times of high usage however transaction gas costs go up and public RPCs can face congestion. It can be advisable to have your own endpoint, particularly if you are using gTrade with large amounts of collateral. This may decrease latency when submitting trades, and may allow you to pay higher gas during congested conditions.

***Note:** Our website already uses cutting-edge technology to work around RPC instability. Instead of using the Metamask RPC to show the trades on the website, it uses its own internal list of dedicated RPCs and streams them to the frontend. This means that the RPC in Metamask is only used to send transactions.*\
\
If using a public RPC, it is highly advisable to have more than one available in Metamask so that you can switch quickly if you were to find that one was not as responsive as you'd like.&#x20;

Public RPCs:

* <https://rpc-mainnet.matic.quiknode.pro/>
* <https://public-rpc.blockpi.io/http/polygon>
* <https://polygon-rpc.com/>
* <https://rpc-mainnet.matic.network>
* <https://matic-mainnet.chainstacklabs.com><br>

There are many different sites on which you can get a polygon endpoint of your own. \
Some are paid and some offer free and paid options:

* <https://moralis.io/>
* <https://chainstack.com/>
* <https://www.alchemy.com/>
* <https://www.quicknode.com/>
* <https://getblock.io/>
* <https://infura.io/>

For instance, for a free Chainstack endpoint:

1\. Go to [chainstack.com](https://chainstack.com/). Sign up. Go to your dashboard.

2\. Click create project. Type in any name. Leave it as public chain and hit create.

3\. Click on your project and click add a node. You can use a free one. Set it to polygon mainnet.

4\. Wait for it to create, this will take a few minutes. Then click it.

5\. Copy the https\://... address you get and create a new metamask network for polygon with this as the endpoint.

6\. You can now pay >1 MATIC for each transaction.


# Arbitrum Network Setup

When selecting the Arbitrum Network (if you do not have it added already to Metamask), you will be prompted to add it.&#x20;

### What is Arbitrum One/Nitro/Nova? How does it differ from Ethereum?

Arbitrum One and Arbitrum Nova are two networks developed by Offchain Labs. Both run on a technology called Nitro. gTrade exists on Arbitrum One, the most use Arbitrum network. A more in-depth discussion can be found in their medium articles on [Nitro](https://medium.com/offchainlabs/arbitrum-nitro-one-small-step-for-l2-one-giant-leap-for-ethereum-bc9108047450) and [Arbitrum Nova](https://medium.com/offchainlabs/introducing-nova-arbitrum-anytrust-mainnet-is-open-for-developers-9a54692f345e#:~:text=Nova%20is%20our%20new%20chain,of%20a%20data%20availability%20committee.).

### Arbitrum Metamask Setup

To add Arbitrum automatically to Metamask go to [Arbiscan](https://arbiscan.io/) and scroll to the bottom. Then click on "Add Network":

<figure><img src="/files/FOfsNruLKCqRJi5luU6l" alt=""><figcaption><p>Scroll to the bottom to see the button to add Arbitrum.</p></figcaption></figure>

See below for more information on RPC endpoints.

After following each step you can now switch between the Ethereum and Arbitrum networks in Metamask as you want.

### Getting Funds to Arbitrum

Arbitrum uses ETH as the native currency to pay for transactions, including to manage trades on gTrade.&#x20;

If you don't have any assets on Arbitrum, there are a number of ways to move them there.&#x20;

1. **The official bridge is** [**Arbitrum bridge**](https://bridge.arbitrum.io/)**.** This takes about 10 minutes.
2. For bridging **GNS** the bridge can be found on the [bridging page](https://gains.trade/bridge).
3. You can use a third party bridge to bridge from other chains. **Please exert caution using any bridge** - always ensure you are not visiting a phishing website by confirming the link you are visiting from a services official page/communication.
   * Bungee (Bridge Aggregator): <https://bungee.exchange/>
   * Synapse: <https://synapseprotocol.com/>
   * Connext: [ https://bridge.connext.network/](< https://bridge.connext.network/>)
4. Some centralised exchanges support withdrawing ETH to Arbitrum. \
   Ensure you have selected Arbitrum One as the chain to withdraw to and not Ethereum.

### RPC Endpoints

RPCs are what Metamask uses to connect to the blockchain, whether to fetch information or to send transactions.

Public RPCs are the easiest way to access the Arbitrum network. During times of high usage however transaction gas costs go up and public RPCs can face congestion. It can be advisable to have your own endpoint, particularly if you are using gTrade with large amounts of collateral. This is less of a factor on Arbitrum compared to Polygon.

***Note:** Our website already uses cutting-edge technology to work around RPC instability. Instead of using the Metamask RPC to show the trades on the website, it uses its own internal list of dedicated RPCs and streams them to the frontend. This means that the RPC in Metamask is only used to send transactions.*\
\
If using a public RPC, it is highly advisable to have more than one available in Metamask so that you can switch quickly if you were to find that one was not as responsive as you'd like.&#x20;

Public RPCs:

* <https://arb1.arbitrum.io/rpc>
* <https://arbitrum.public-rpc.com>

There are many different sites on which you can get an Arbitrum endpoint of your own. \
Some are paid and some offer free and paid options:

* <https://moralis.io/>
* <https://chainstack.com/>
* <https://www.alchemy.com/>
* <https://www.quicknode.com/>
* <https://getblock.io/>
* <https://infura.io/>


# Opening / Closing trades

This guide shows the steps on opening and closing the trade via the [gains.trade](https://gains.trade) frontend.

To open and close trades on gTrade you will need:

1. A Web3 wallet e.g. [Metamask](https://metamask.io/) which is connected to gTrade.
2. MATIC for Polygon/ETH for Arbitrum in that wallet to pay for transaction fees.
3. DAI, USDC, or WETH in that wallet to use as collateral.<br>

**Interface Overview**

These are the different areas of trading UI that this guide will be using.

![](/files/chgL42wK1SdgJTzLykfP)

**Opening a trade**

**1.** Go to our [platform](https://gains.trade/decentralized-trading/).

**2.** Click "Connect Wallet" in the top right. You might need to refresh the page for the website to detect your wallet, if it wasn't unlocked yet.

**3.** If this is your first trade, you will need to approve the contract to be able to use the collateral that you want it to. Click approve and submit the transaction to Polygon or Arbitrum.

![Approve to allow the contract you use DAI as collateral.](/files/iRq9r0J27EGRlw3zfbT3)

**4.** Use the "Add Pair +" button to select the pair you want to trade on.  Favourite it if you want to save it into your trading interface. You will notice below that "Hide closed" is ticked - hiding forex and commodities markets when they are closed.

![](/files/KNFXMudgBGDSVsWezTTN)

**5.** Now, you can set your trade parameters:

1. **Trade Type** and whether it is **long (buy) or short (sell)**.
   1. **Market:** To be used to open a trade immediately. It will open at the market price (+ spread).
   2. **Limit**: To be used when you want to go long at a lower price than present, or to go short if the price reaches a higher price than present. Executes at exact price set if price reaches threshold + spread.
   3. **Stop Limit:** To be used when you want to go long if the price reaches a higher price than present, or to go short if the price reaches a lower price than present. You might want to use this to long a breakout, or short a breakdown. The execution price is the current market price + spread.
2. **Collateral:** maximum amount you are risking if you are liquidated. Your collateral x leverage must be above the minimum position size. For example on cryptos, it should be above 1,500 USD. This means you can for example open a trade with 50 DAI collateral at 30x, or with 300 DAI at 5x leverage, etc. Or if opening a trade with .1 ETH at market value of $2500 ETH / USD, you would need minimum 6 leverage.
3. **Leverage:** multiply the volatility of the price up and down, to increase exposure.
4. **Max slippage:** Used to cancel a market order automatically if the price moved too fast in the direction of the trade before it was opened. For example if you wish to market long the current price but before your trade is opened the price moved up 1%, it will cancel automatically.
5. **Your Stop Loss and Take Profit.** You are not obligated to use a stop loss, but your trade will be liquidated if it reaches the [liquidation threshold](/gtrade-leveraged-trading/fees-and-spread#liquidation-thresholds), which is outlined in this [Medium article](https://gainsnetwork-io.medium.com/v9-2-enhanced-spread-formula-and-competitive-liquidations-9cd99ea3497e).\
   \&#xNAN;*Please note that Stop Losses for BTC and ETH are guaranteed, and in times of high network congestion your Stop Loss might not immediately trigger. It is important that you don't manually close your order since this will void the guaranteed Stop Loss (at your set price) and count as a Market Close (at the price when it gets triggered).*

![Left: This trade is longing eth on a Market open at 100x leverage with no stop loss and a take profit of 900&. Slippage is set to 1%.
Right: Metamask popup with gas automatically suggested - just need to hit confirm to sent the transaction to the network.](/files/wMR8aA6049FyaOj76HJW)

You can then click on the order execution button, which displays the order type and direction you will be executing. In our case it says **"MARKET LONG"**. This brings up the Web3 popup to send the transaction to Polygon or Arbitrum and open the order. High gas is automatically suggested to ensure that trades are executed quickly.

After the transaction is submitted you will see the number of confirmations required to display it on the front end. Once 2 blocks have passed, it is displayed in the section named "Your Open Trades".

**Order Initiated:** This is the moment that your request to execute an order reaches the network.\
**Executed:** This is the moment your trade is executed, when our Chainlink DON returns the current price. In the below example the price has just been returned.

You can read more about the block confirmations [here](https://docs.gains.trade/gtrade-leveraged-trading/pages/ir9BRbKNOi7e6nrZAKwv#17.-what-is-the-0-5-confirmations-that-appears).

![First the order initiates, then it is executed.](/files/bxg00Mm1IhFGypxFaGyk)

**Viewing the details of an Open Trade & Updating TP/SL**

Now your trade is open, you can view its details by clicking on it under Your Open Trades. You can also see the liquidation price marked in blue on the chart, and if you have them set you will see TP/SL lines in green/red respectively.

![An active trade in Your Open Trades.](/files/Dk2RsM1BBwTSDs5pQ9wi)

By clicking on your trade, you can view its details. If you click on the TP/SL price you will see the prompt to update these - you can input the price desired to TP/SL and it will show you what % that would be in relation to your collateral. If you don't have a TP/SL it will show "None".

![The displayed Net PnL is what you will receive back to your wallet at the moment of closure registering on chain.](/files/icdsPSLw9RsooGB5SDxT)

More details on fees can be found [here](/gtrade-leveraged-trading/fees-and-spread).

**Closing a trade**

1. &#x20;Click on the X to the right hand side of your trade in Your Open Trades

![The X to the right will let you close your trade.](/files/4rCMxZl92rXnsmPFnk3i)

1. Confirm in Metamask to send the closure to Polygon or Arbitrum.
2. Await Trade Closure Confirmation - This is what you receive to your wallet.

![Closure of the trade.](/files/343ys225VrcdM7KIV6cJ)


# Trade Collaterals

gTrade offers multiple collateral options

gTrade offers $USDC, $DAI, $WETH, and $APE for trading, enhancing flexibility and user choice. (Please note that not all collaterals are available to every chain.)

#### Key Features:

1. **Synthetic Trading Flexibility**: gTrade follows a synthetic trading architecture, allowing traders to trade using $USDC, $DAI, $WETH, or $APE as collateral. This innovative approach means you're not buying or selling the underlying assets directly but are instead trading on their price movements.
2. **Fees in Collateral**: Trading fees are paid in the collateral used, streamlining transactions and aligning with your trading strategy.
3. **Risk Management**: gTrade manages risk at a collateral level, as each is backed by its own gToken vault and separate liquidity. Meaning that if $USDC open interest were to be maxed out, this would not affect the open interest for other collaterals.
4. **Collateral-based Position Sizing**: Position size is determined in the collateral type, not the traded asset nor its notional value. This approach simplifies liquidation risk management by keeping the position size constant, independent of collateral price movements, making trading strategies clearer and more predictable (more details on the next page).

#### Advantages:

Our model eases liquidation risk management. Unlike traditional exchanges where a position's leverage and liquidation risk fluctuate with collateral price changes, our stable model allows for better strategy planning and a stress-reduced trading experience. By offering diverse collateral options and simplifying fees and risk management, we aim to improve the trading experience, empowering traders with control and flexibility in their strategies.

#### Maximum available interest (max OI)

The max OI is a separate value for each vault. It is calculated as follows:

`maxOi` = `(vaultExposure * vaultTvl / avgDailyAtr^atrExponent * atrMultiplier) * oiFactor / correlation * logPairCount`

where:

* `vaultExposure` = adjustable constant
* `vaultTvl` = `tvl + 5 * overCollat + .15 * (gnsMarketCap * (tvl + 5 * overCollat) / (allVaultTvls + 5 * allVaultOverCollats))`
* `avgDailyAtr` = computed from past 5 day candles
* `atrExponent` = adjustable constant
* `atrMultiplier` = adjustable constant
* `oiFactor` = \[0,1] - a throttle on OI based on group or pair
* `correlation` = \[0,1] - avg correlation of pairs in group, or just 1 if pair
* `logPairCount` = `numPairsInGroup^.25`


# Spotlight: WETH

Highlighting execution differences between gTrade and a traditional CEX

{% hint style="info" %}
For demonstration we use $ETH even though on gTrade it is $WETH
{% endhint %}

It is important to understand the subtle difference between CEXes and gTrade:

* In most CEXes, the trader’s collateral is in ETH and this opens a position on a pair with a fixed position size in token amount (underlying pair). The current leverage of the position changes not only with the pair price, but also with ETH price. Therefore, the liquidation price is also changing with ETH price.
* On gTrade, the trader’s collateral is also in ETH but they open a position on a pair with a **fixed position size in ETH amount**, which is variable in token amount (underlying pair). The main advantage of this design is that the liquidation price becomes independent of ETH price. Any changes on ETH price does not impact the current leverage of the position. As a result, managing the liquidation risk is a lot more intuitive and easier on gTrade.

Illustrative example :

* Trader1 has 1 ETH as collateral on a CEX
* Trader2 has 1 ETH as collateral on gTrade
* ETH price = $2,000
* Both traders want to open a 10x long position on the pair TIA
* TIA price = $10

***

On the **CEX**, Trader 1 opens 10x leverage long in the pair TIA.

His position size is 2,000 TIA (notional position size = $20,000 at inception). This position size does not change during the life-cycle of the position. If ETH drops to $1,900, his position size is still 2,000 TIA.

However, on CEXes, the current leverage is a function of both ETH and TIA price, and the liquidation price is a function of ETH (and the funding). So when ETH drops to $1,900, trader’s liquidation price is lowered and get closer. This is not ideal to manage.

***

On **gTrade**, Trader 2 opens 10x leverage long in the pair TIA

His position size is 10 ETH (notional position size = $20,000) = 2,000 TIA. The position size in ETH does not change during the lifecycle of the position; but the position size in TIA amount is variable.

To illustrate this, assume the price of ETH is now $1,900 and TIA price remains unchanged at $10.

Now his position size 10 ETH is equivalent to a notional position size of $19,000 = 1900 TIA

Conversely, if ETH price increases to $2,100 and TIA price is still unchanged, his position size of 10 ETH is equivalent to a notional position size of $21,000 = 2100 TIA.

***

In Scenario 1 where ETH price decreases, the notional position size also decreases : as a result, the trader will lose less money if TIA price declines, and will earn less money if TIA price increases.

In Scenario 2 where ETH prices increases, the notional position size also increases : this boosts the trader’s P\&L in both direction, meaning if TIA price increases, he trader earns more; but if TIA price decreases, the trader also loses more.

But in both Scenarios, the powerful feature on gTrade is that the trader’s liquidation price remain unchanged in both scenarios : it is completely independent from price variation on ETH. This makes managing liquidation risk a lot easier.


# Asset classes

In the next pages you will find details regarding each asset class listed on gTrade.


# Cryptocurrencies

Our unique architecture enables leverage trading on crypto pairs prices.

### Introduction

gTrade currently offers trading on the price of over 220 crypto pairs at leverage ranges of 1.1x to 500x.

Please refer to the[ Pair List ](/gtrade-leveraged-trading/pair-list)page to see a full list of the pairs currently offered.

### Market Times

Crypto markets are open 24/7, which means you can trade whenever you want. However, when the stock market is closed, there is generally less volume on cryptos as well, and therefore less volatility.

### Guaranteed execution

As crypto markets never close, there aren't any gaps. This means that for pairs with 0% price impact (spread), we can guarantee your stop loss regardless of the time it takes to execute. It will always be triggered at the exact price you set.\
\&#xNAN;*Please note that Stop Losses for BTC and ETH are guaranteed, and in times of high network congestion your Stop Loss might not immediately trigger. It is important that you don't manually close your order since this will void the guaranteed Stop Loss (at your set price) and count as a Market Close (at the price when it gets triggered).*


# Forex

Our unique architecture enables leverage trading on forex pairs prices.

### Introduction

gTrade currently offers trading on the price of over 30 forex pairs at leverage ranges of 10x to 1000x.

Please refer to the[ Pair List ](/gtrade-leveraged-trading/pair-list)page to see a full list of the pairs currently offered.

### Market Times

Unlike crypto markets, forex markets are not always open. Times are referenced in ET (New York time).

<table><thead><tr><th width="230.4285714285714">Day of the week</th><th width="150">Market Open / Close</th></tr></thead><tbody><tr><td>Monday</td><td>Open all day</td></tr><tr><td>Tuesday</td><td>Open all day</td></tr><tr><td>Wednesday</td><td>Open all day</td></tr><tr><td>Thursday</td><td>Open all day</td></tr><tr><td>Friday</td><td>Closed from 4 PM (DST) or 5 PM (non-DST)</td></tr><tr><td>Saturday</td><td>Closed all day</td></tr><tr><td>Sunday</td><td>Open from 4 PM (DST) or 5 PM (non-DST)</td></tr></tbody></table>

Additionally, these are the following **holidays** where market are closed or closes early. Times are referenced in ET (New York time):

* April 3, 2026: Good Friday
* May 25, 2026: Memorial Day
* June 19, 2026: Juneteenth National Independence Day
* July 2, 2026: Day Before Independence Day (closes early at 1pm)
* July 3, 2026: Independence Day
* September 7, 2026: Labor Day
* November 26, 2026: Thanksgiving Day
* November 27, 2026: Black Friday (closes early at 1pm)
* December 24, 2026: Christmas Eve (closes early at 12:45pm)
* December 25, 2026: Christmas Day
* December 31, 2026: New Year's Eve (closes early at 4pm)
* January 1, 2027: New Year's Day
* January 18, 2027: Martin Luther King, Jr. Day
* March 26, 2027: Good Friday
* May 31, 2027: Memorial Day

### Gaps

As there price of forex pairs can change while the market is closed, this can result in gaps, where the market opens at a different price than the price it closed at last time it was open.

Due to this, we cannot guarantee stop losses, which means you have to be careful with keeping trades open while the market is closed. It could be liquidated because of a big gap in the opposite direction once market opens. It could also result in a bigger win than you initially planned for, as volatility works on both sides. Please take this into consideration when using high leverage.

### Reduced Leverage/Increased Spread

The max leverage is temporarily reduced and spread is temporarily increased during:

* **Major news events**, from 1 hour before to 10 minutes after the event.
* **Market closing**, starting 30 minutes before the market closes.
* **Low liquidity session**, for 2 hours after New York Stock Exchange closes.


# Commodities

Our unique architecture enables leverage trading on commodities prices.

### Introduction

gTrade currently offers trading on the price of 5 commodities, at leverage ranges of 2x-250x for XAU/USD (Gold) and 2x-150x for XAG/USD (Silver), WTI/USD (Crude Oil), XPT/USD (Platinum), and XPD/USD (Palladium).

Please refer to the[ Pair List ](/gtrade-leveraged-trading/pair-list)page to see a full list of the pairs currently offered.&#x20;

### Market Times

Just like forex markets, the commodities market is not always open. Times are referenced in ET (New York time).

<table><thead><tr><th width="230.4285714285714">Day of the week</th><th width="150">Market Open / Close</th></tr></thead><tbody><tr><td>Monday</td><td>Open apart from 5 PM - 6 PM</td></tr><tr><td>Tuesday</td><td>Open apart from 5 PM - 6 PM</td></tr><tr><td>Wednesday</td><td>Open apart from 5 PM - 6 PM</td></tr><tr><td>Thursday</td><td>Open apart from 5 PM - 6 PM</td></tr><tr><td>Friday</td><td>Open until 5 PM</td></tr><tr><td>Saturday</td><td>Closed all day</td></tr><tr><td>Sunday</td><td>Open from 6 PM</td></tr></tbody></table>

Additionally, these are the following **holidays** where market are closed or closes early. Times are referenced in ET (New York time):

* April 2, 2026: Maundy Thursday (closes early at 1pm)
* April 3, 2026: Good Friday
* May 25, 2026: Memorial Day
* June 19, 2026: Juneteenth National Independence Day
* July 2, 2026: Day Before Independence Day (closes early at 1pm)
* July 3, 2026: Independence Day
* September 7, 2026: Labor Day
* November 26, 2026: Thanksgiving Day
* November 27, 2026: Black Friday (closes early at 1pm)
* December 24, 2026: Christmas Eve (closes early at 12:45pm)
* December 25, 2026: Christmas Day
* December 31, 2026: New Year's Eve (closes early at 4pm)
* January 1, 2027: New Year's Day
* January 18, 2027: Martin Luther King, Jr. Day (closes at 1pm, reopens at 6pm)
* February 15, 2027: Presidents' Day (closes at 2:30pm, reopens at 6pm)
* March 26, 2027: Good Friday
* May 31, 2027: Memorial Day

### Gaps

As the price of commodities can change while the market is closed, this can result in gaps, where the market opens at a different price than the price it closed at last time it was open.

Due to this, we cannot guarantee stop losses, which means you have to be careful with keeping trades open while the market is closed. It could be liquidated because of a big gap in the opposite direction once market opens. It could also result in a bigger win than you initially planned for, as volatility works on both sides. Please take this into consideration when using high leverage.

### Reduced Leverage/Increased Spread

The max leverage is temporarily reduced and spread is temporarily increased during:

* **Major USD news events**, from 1 hour before to 10 minutes after the event.
* **Market closing**, starting 30 minutes before the market closes.


# Stocks

Our unique architecture enables leverage trading on stocks prices.

### Introduction

gTrade offers trading on the prices of an ever-growing number of stocks, at leverage ranges of 1.1x to 50x. Stocks are available on Arbitrum, Base, and Solana.

Please refer to the [Pair List](/gtrade-leveraged-trading/pair-list) page to see a full list of the pairs currently offered.&#x20;

### Market Times

As with all RWA markets, the stock market is not always open. Times are referenced in ET (New York time). Positions remain open when the market is closed, but it's not possible to open, close, or otherwise edit positions during this time. [Please see more info below](#gaps).

<table><thead><tr><th width="230.4285714285714">Day of the week</th><th width="150">Market Open / Close</th></tr></thead><tbody><tr><td>Monday</td><td>9.30am — 4pm</td></tr><tr><td>Tuesday</td><td>9.30am — 4pm</td></tr><tr><td>Wednesday</td><td>9.30am — 4pm</td></tr><tr><td>Thursday</td><td>9.30am — 4pm</td></tr><tr><td>Friday</td><td>9.30am — 4pm</td></tr><tr><td>Saturday</td><td>Closed all day</td></tr><tr><td>Sunday</td><td>Closed all day</td></tr></tbody></table>

Additionally, these are the following **holidays** where market are closed or closes early. Times are referenced in ET (New York time):

* April 3, 2026: Good Friday
* May 25, 2026: Memorial Day
* June 19, 2026: Juneteenth National Independence Day
* July 2, 2026: Day Before Independence Day (closes early at 1pm)
* July 3, 2026: Independence Day
* September 7, 2026: Labor Day
* November 26, 2026: Thanksgiving Day
* November 27, 2026: Black Friday (closes early at 1pm)
* December 24, 2026: Christmas Eve (closes early at 1pm)
* December 25, 2026: Christmas Day
* January 1, 2027: New Year's Day
* January 18, 2027: Martin Luther King, Jr. Day
* February 15, 2027: Presidents' Day
* March 26, 2027: Good Friday
* May 31, 2027: Memorial Day

### Gaps

As the price of stocks can change while the market is closed, this can result in gaps, where the market opens at a different price than the price it closed at last time it was open.

Due to this, gTrade cannot guarantee stop losses to hit, which means you have to be careful with keeping trades open while the market is closed. It could be liquidated because of a big gap in the opposite direction once market opens. It could also result in a bigger win than you initially planned for, as volatility works on both sides. Please take this into consideration when using high leverage.

### Reduced Leverage/Increased Spread

The max leverage is temporarily reduced and spread is temporarily increased during:

* **Major USD news events**, from 1 hour before to 10 minutes after the event.
* **Market closing**, starting 30 minutes before the market closes.
* **Earnings and dividends**, starting the day before.

*Exact timing and parameters may vary. Please note that this applies when opening new trades, and does not impact already open trades.*

### Access

*Please note that stock trading is not accessible to users located in the United States or other OFAC-sanctioned regions. Access is automatically restricted based on IP and other geolocation methods.*


# Indices

Our unique architecture enables leverage trading on index prices.

### Introduction

gTrade currently offers trading on the price of 4 indices, at leverage ranges of 1.1x-100x. Indices are available on Arbitrum, Base, and Solana.

Please refer to the [Pair List](/gtrade-leveraged-trading/pair-list) page to see a full list of the pairs currently offered.&#x20;

### Market Times

As with all RWA markets, the indices market is not always open. Times are referenced in ET (New York time). Positions remain open when the market is closed, but it's not possible to open, close, or otherwise edit positions during this time. [Please see more info below](#gaps).

<table><thead><tr><th width="230.4285714285714">Day of the week</th><th width="150">Market Open / Close</th></tr></thead><tbody><tr><td>Monday</td><td>9.30am — 4pm</td></tr><tr><td>Tuesday</td><td>9.30am — 4pm</td></tr><tr><td>Wednesday</td><td>9.30am — 4pm</td></tr><tr><td>Thursday</td><td>9.30am — 4pm</td></tr><tr><td>Friday</td><td>9.30am — 4pm</td></tr><tr><td>Saturday</td><td>Closed all day</td></tr><tr><td>Sunday</td><td>Closed all day</td></tr></tbody></table>

Additionally, these are the following **holidays** where market are closed or closes early. Times are referenced in ET (New York time):

* April 3, 2026: Good Friday
* May 25, 2026: Memorial Day
* June 19, 2026: Juneteenth National Independence Day
* July 2, 2026: Day Before Independence Day (closes early at 1pm)
* July 3, 2026: Independence Day
* September 7, 2026: Labor Day
* November 26, 2026: Thanksgiving Day
* November 27, 2026: Black Friday (closes early at 1pm)
* December 24, 2026: Christmas Eve (closes early at 12:15pm)
* December 25, 2026: Christmas Day
* December 31, 2026: New Year's Eve (closes early at 4pm)
* January 1, 2027: New Year's Day
* January 18, 2027: Martin Luther King, Jr. Day
* February 15, 2027: Presidents' Day
* March 26, 2027: Good Friday
* May 31, 2027: Memorial Day

### Gaps

As the price of indices can change while the market is closed, this can result in gaps, where the market opens at a different price than the price it closed at last time it was open.

Due to this, gTrade cannot guarantee stop losses to hit, which means you have to be careful with keeping trades open while the market is closed. It could be liquidated because of a big gap in the opposite direction once market opens. It could also result in a bigger win than you initially planned for, as volatility works on both sides. Please take this into consideration when using high leverage.

### Reduced Leverage/Increased Spread

The max leverage is temporarily reduced and spread is temporarily increased during:

* **Major USD news events**, from 1 hour before to 10 minutes after the event.
* **Market closing**, starting 30 minutes before the market closes.

*Exact timing and parameters may vary. Please note that this applies when opening new trades, and does not impact already open trades.*

### Access

*Please note that index trading is not accessible to users located in the United States or other OFAC-sanctioned regions. Access is automatically restricted based on IP and other geolocation methods.*


# Fees & Spread

## Introduction

In line with industry standard, **fees are calculated on the value of the total position size** (leverage x collateral).

1. [Fees Breakdown](#fees-breakdown)
   1. [Cryptocurrencies](#cryptocurrencies)
   2. [Forex](#forex-major)
   3. [Commodities](#commodities-tier-1)
   4. [Revenue Distribution](#revenue-distribution)
2. [Lifecycle of a Trade](#undefined)
   1. [Opening Fee](#opening-fee)
   2. [Spread](#spread)
   3. [Price Impact](#price-impact)
   4. [Borrowing Fees](#rollover-and-borrowing-fees)
   5. [Dynamic Liquidation Prices](#dynamic-liquidation-prices)
   6. [Closing Fee](#closing-fee)

## Fees Breakdown

The "Market/Limit" fee below goes to [Buyback & Distribute](/liquidity-farming-pools/gns-staking#buyback-and-distribute) if the order is a market order, and to oracle bots if the order is a limit order.

Additionally, the referrer rewards are always taken from the "Governance Fund" fees.

Finally, while all trades are open, they may pay a [borrowing fee](#borrowing-fee), which goes into the overcollateral layer of the corresponding gToken vault.

Gains Network earns revenue from trading fees on gTrade, its decentralized leveraged trading platform. The fees are distributed as follows:

• Governance (DAO): 22% for protocol operations and incentives\
• Vault (Liquidity Providers): 15% for underwriting trades\
• GNS Burn Mechanism: 54% to support token utility\
• Referrals: 5%\
• Trigger Keepers: 4%

### Cryptocurrencies

For BTC and ETH, the spread is 0%. For other cryptocurrencies the spread is dynamic, depending on the [price impact formula](#dynamic-spread).

**Core**

1. **Opening a trade: 0.05%**
2. **Closing a trade: 0.05%**

**Non-core**

1. **Opening a trade: 0.06%**
2. **Closing a trade: 0.06%**

### Forex (Major)

Spreads on all major forex pairs are fixed at 0.01%.

1. **Opening a trade: 0.012%**
2. **Closing a trade: 0.012%**

### Forex (Minor)

Spreads on all minor pairs are fixed at 0.01%.

1. **Opening a trade: 0.016%**
2. **Closing a trade: 0.016%**

### Forex (Exotic)

Spreads on all exotic forex pairs are set per pair depending on their volatility.

1. **Opening a trade: 0.02%**
2. **Closing a trade: 0.02%**

### Commodities (Tier 1)

This category currently only includes XAU/USD (Gold). Spreads on all tier 1 commodities are fixed at 0.01%.

1. **Opening a trade (0.05%)**
2. **Closing a trade (0.05%)**

### Commodities (Tier 2)

This category currently includes XAG/USD (Silver), WTI/USD (Oil), XPD/USD (Palladium), and XPT/USD (Platinum). Spreads on all tier 2 commodities are fixed at 0.04%.

1. **Opening a trade: 0.08%**
2. **Closing a trade: 0.08%**

### Stocks

1. **Opening a trade: 0.07%**
2. **Closing a trade: 0.07%**

### Indices

1. **Opening a trade: 0.05%**
2. **Closing a trade: 0.05%**

## **Lifecycle of a Trade**

### Opening Fee

Let's say we use **250 USDC** at **10x** leverage to long ETH/USD. The fee is applied to leveraged amount: **2,500 USDC**.

2,500 \* (0.06/100) = **1.5 USDC fee**

**248.5 USDC** is the total collateral value of your newly opened trade, and therefore its total position size is **2,485 USDC**.

### **Fixed Spread**

When opening a trade the Chainlink oracle returns a price for the asset, for instance 3,003.19. The spread is then taken into account (0.04%), so the open price would be **3004.39** before consideration of the dynamic spread (see section below).

That is: 3,003.19 + (3,003.19 \* 0.04 / 100) = **3004.39**

Please make note that the spread is different for each pair — smaller pairs with lower liquidity have a higher spread. It is displayed on the front end next to the Price in the Trade Parameters box, and can be confirmed in the [Pairs Storage](/what-is-gains-network/contract-addresses) contract by searching for the relevant [pair index](/gtrade-leveraged-trading/pair-list).

### Dynamic Spread&#x20;

Dynamic Spread, formerly known as 'Price Impact' is added on top of the fixed spread (if the pair has one). It depends on the open interest of the pair, the position size of the trade being opened, and on the direction of the trade (long / short).

***Dynamic Spread (%) =** (Open interest {long/short} + New trade position size / 2) / 1% depth {above/below}.*

#### Cryptocurrencies

Dynamic spreads using the 1% depth in each direction (long: 1% depth above / short: 1% depth below) from Binance.

**Forex**

Fixed spreads.

**Commodities**

Fixed spreads.

### **ETH/USD Example**

So using our above price example with a position size of 2,480 after fees, if the "1% depth above price" parameter for ETH/USD is 8m and there is 100,000 USDC of open long interest:

**(100,000 + 2,480 / 2) / 8,000,000 = 0.0126% dynamic spread**

This percentage is then applied to the opening price including the Fixed Spread. In the case of crypto, as there is no Fixed Spread, this is just 3,003.19:

**Final opening price =** 3003.19 + (3003.19 \* 0.0126 / 100) = 3003.57

So in this case if the median spot price was 3003.19, the opening price would be 3003.57.

### **Borrowing Fee**s

Borrowing fees are applied to trades while they are open.&#x20;

### Borrowing Fee

Borrowing fees treat open trades of the dominant side as vault borrowers. The fee is determined by a pair's (or the group the pair is part of) net OI relative to the overall vault TVL, meaning pairs (or groups) with more lopsided OI will charge more than pairs with balanced OI.&#x20;

The fee is charged per block on a trade's total position size and is calculated as follows:

`feePerBlock = baseFeePerBlock * (effectiveOi / maxOi) ^ exponent`

where `effectiveOi` is calculated as follows:

`effectiveOi = Math.min(Math.max(Math.abs(long - short), max * minP), max * maxP)`

`effectiveOi` is calculated by finding the delta between the side that is long and the side that is short. This value is then clamped using `minP` and `maxP` to create a floor and a ceilling, ensuring that both a minimum fee is always paid, and that the fee is never excessive. `exponent` is used to maintain an exponential relationship between the borrowing fee and the current market conditions.

Although outdated, please refer to the [Medium article for further details](https://gainsnetwork-io.medium.com/gtrade-v6-3-2-from-funding-fees-to-borrowing-fees-ee3d747b0b70).

### Liquidation Prices

Trades liquidation prices can **get closer** over time if you **pay borrowing fees**.

***Liquidation Price Distance =** Open Price \* (Collateral \** [*Liquidation Threshold*](#liquidation-thresholds) *- Closing Fee - Borrowing Fees) / Collateral / Leverage.*

**Liquidation price =** \
If Long: Open Price - Liquidation Price Distance\
Else (Short): Open Price + Liquidation Price Distance.

For example, let's say that you have opened a long on BTC/USD at 20,000 USD using 100x leverage and 50 USDC collateral, the liquidation threshold would be 67%, the closing fee would be 16 USDC (20,000\*(0.08/100) and that you have paid 1 USDC in borrowing fees:

**Liquidation Price =** 20,000 - 20,000 \* (50 \* 0.67 - 16 - 1) / 50 / 100 = 19,888 USD.

### Liquidation Thresholds

The liquidation threshold depends on asset class and leverage used. The values can be found in the following table, for *Cryptocurrencies, Forex (major), Forex (minor), Forex (exotic), Commodities (gold), Commodities (other)*

{% tabs %}
{% tab title="Cryptocurrencies" %}
**Cryptocurrencies**

| Leverage     | Liquidation Threshold % |
| ------------ | ----------------------- |
| 2            | 89.84                   |
| 5            | 89.60                   |
| 10           | 89.20                   |
| 15           | 88.80                   |
| 20           | 88.40                   |
| 25           | 88.00                   |
| 30           | 85.46                   |
| 35           | 82.91                   |
| 40           | 80.37                   |
| 45           | 77.83                   |
| 50           | 75.29                   |
| 55           | 72.74                   |
| 60           | 70.20                   |
| 65           | 69.80                   |
| 70           | 69.40                   |
| 75           | 69.00                   |
| 80           | 68.60                   |
| 85           | 68.20                   |
| 90           | 67.80                   |
| 95           | 67.40                   |
| 100          | 67.00                   |
| 105          | 66.60                   |
| 110          | 66.20                   |
| 115          | 65.80                   |
| 120          | 65.40                   |
| 125          | 65.00                   |
| 130          | 64.60                   |
| 135          | 64.20                   |
| 140          | 63.80                   |
| 145          | 63.40                   |
| 150          | 63.00                   |
| {% endtab %} |                         |

{% tab title="Fx (major)" %}
**Forex (major)**

| Leverage     | Liquidation Threshold % |
| ------------ | ----------------------- |
| 2            | 89.98                   |
| 25           | 89.70                   |
| 50           | 89.40                   |
| 75           | 89.10                   |
| 100          | 88.80                   |
| 125          | 86.63                   |
| 150          | 84.45                   |
| 175          | 82.28                   |
| 200          | 80.10                   |
| 225          | 77.93                   |
| 250          | 75.75                   |
| 275          | 73.58                   |
| 300          | 71.40                   |
| 325          | 71.10                   |
| 350          | 70.80                   |
| 375          | 70.50                   |
| 400          | 70.20                   |
| 425          | 69.90                   |
| 450          | 69.60                   |
| 475          | 69.30                   |
| 500          | 69.00                   |
| 525          | 68.70                   |
| 550          | 68.40                   |
| 575          | 68.10                   |
| 600          | 67.80                   |
| 625          | 67.50                   |
| 650          | 67.20                   |
| 675          | 66.90                   |
| 700          | 66.60                   |
| 725          | 66.30                   |
| 750          | 66.00                   |
| 775          | 65.70                   |
| 800          | 65.40                   |
| 825          | 65.10                   |
| 850          | 64.80                   |
| 875          | 64.50                   |
| 900          | 64.20                   |
| 925          | 63.90                   |
| 950          | 63.60                   |
| 975          | 63.30                   |
| 1000         | 63.00                   |
| {% endtab %} |                         |

{% tab title="Fx (minor)" %}
**Forex (minor)**

| Leverage     | Liquidation Threshold % |
| ------------ | ----------------------- |
| 2            | 89.97                   |
| 25           | 89.60                   |
| 50           | 89.20                   |
| 75           | 88.80                   |
| 100          | 85.54                   |
| 125          | 82.29                   |
| 150          | 79.03                   |
| 175          | 75.77                   |
| 200          | 72.51                   |
| 225          | 69.26                   |
| 250          | 66.00                   |
| 275          | 65.60                   |
| 300          | 65.20                   |
| 325          | 64.80                   |
| 350          | 64.40                   |
| 375          | 64.00                   |
| 400          | 63.60                   |
| 425          | 63.20                   |
| 450          | 62.80                   |
| 475          | 62.40                   |
| 500          | 62.00                   |
| 525          | 61.60                   |
| 550          | 61.20                   |
| 575          | 60.80                   |
| 600          | 60.40                   |
| 625          | 60.00                   |
| 650          | 59.60                   |
| 675          | 59.20                   |
| 700          | 58.80                   |
| 725          | 58.40                   |
| 750          | 58.00                   |
| {% endtab %} |                         |

{% tab title="Fx (exotic)" %}
**Forex (exotic)**

| Leverage     | Liquidation Threshold % |
| ------------ | ----------------------- |
| 2            | 89.96                   |
| 25           | 89.50                   |
| 50           | 89.00                   |
| 75           | 84.33                   |
| 100          | 79.67                   |
| 125          | 75.00                   |
| 150          | 70.33                   |
| 175          | 65.67                   |
| 200          | 61.00                   |
| 225          | 60.50                   |
| 250          | 60.00                   |
| 275          | 59.50                   |
| 300          | 59.00                   |
| 325          | 58.50                   |
| 350          | 58.00                   |
| 375          | 57.50                   |
| 400          | 57.00                   |
| 425          | 56.50                   |
| 450          | 56.00                   |
| 475          | 55.50                   |
| 500          | 55.00                   |
| {% endtab %} |                         |

{% tab title="Commodities (gold)" %}
**Commodities (gold)**

| Leverage     | Liquidation Threshold % |
| ------------ | ----------------------- |
| 2            | 89.90                   |
| 10           | 89.50                   |
| 20           | 89.00                   |
| 30           | 87.50                   |
| 40           | 85.00                   |
| 50           | 82.50                   |
| 60           | 80.00                   |
| 70           | 77.50                   |
| 80           | 75.00                   |
| 90           | 72.50                   |
| 100          | 70.00                   |
| 110          | 69.50                   |
| 120          | 69.00                   |
| 130          | 68.50                   |
| 140          | 68.00                   |
| 150          | 67.50                   |
| 160          | 67.00                   |
| 170          | 66.50                   |
| 180          | 66.00                   |
| 190          | 65.50                   |
| 200          | 65.00                   |
| 210          | 64.50                   |
| 220          | 64.00                   |
| 230          | 63.50                   |
| 240          | 63.00                   |
| 250          | 62.50                   |
| {% endtab %} |                         |

{% tab title="Commodities (other)" %}
**Commodities (other)**

| Leverage      | Liquidation Threshold % |
| ------------- | ----------------------- |
| 2             | 89.84                   |
| 5             | 89.60                   |
| 10            | 89.20                   |
| 15            | 88.80                   |
| 20            | 88.40                   |
| 25            | 88.00                   |
| 30            | 84.74                   |
| 35            | 81.49                   |
| 40            | 78.23                   |
| 45            | 74.97                   |
| 50            | 71.71                   |
| 55            | 68.46                   |
| 60            | 65.20                   |
| 65            | 64.80                   |
| 70            | 64.40                   |
| 75            | 64.00                   |
| 80            | 63.60                   |
| 85            | 63.20                   |
| 90            | 62.80                   |
| 95            | 62.40                   |
| 100           | 62.00                   |
| 105           | 61.60                   |
| 110           | 61.20                   |
| 115           | 60.80                   |
| 120           | 60.40                   |
| 125           | 60.00                   |
| 130           | 59.60                   |
| 135           | 59.20                   |
| 140           | 58.80                   |
| 145           | 58.40                   |
| 150           | 58.00                   |
| {% endtab %}  |                         |
| {% endtabs %} |                         |

### Closing Fee

Let's say ETH/USD **went up 1%** from the open price, and we close the trade at **3,033.6**. The pending profit (PnL) will be 1% of 2480 (our leveraged collateral), which is **24.85 USDC**.

Now, we close the trade, and therefore pay the closing fee. Please note that the fees are always applied on the initial position size (without PnL).

2485 \* (0.06/100) = 1.988 USDC closing fee

\--> 24.85 - 1.988 = **22.862 USDC PnL**

Now let's also say that the trade **paid 0.5 USDC** of **borrowing fees**:

22.862 - 0.5 = **22.362 USDC final PnL**

Therefore, you would receive **270.862 USDC** (248.5 USDC collateral + 22.362 PnL) to your wallet after closing your trade.


# Pair List

This is a list of gTrade trading pairs, their relevant pairIndex, and the asset class. \
\
**The pairIndex:**

* Is useful in the case of needing to interact with the contracts directly.
* Reflects the chronological order the asset was added to gTrade.
* Includes pairs that are no longer listed, but kept for technical reasons.

**Please note:**

* Stock splits are indicated by a trailing `_1`
* Not all pairs are available for all chains and/or all collaterals
* Pairs may be disabled automatically (temporarily) for reasons including, but not limited to, price feed anomalies, events that impact the underlying asset, etc

| pairIndex | Asset Class    | Pair           | Active |
| --------- | -------------- | -------------- | ------ |
| 0         | Crypto         | BTC/USD        | ✅      |
| 1         | Crypto         | ETH/USD        | ✅      |
| 2         | Crypto         | LINK/USD       | ✅      |
| 3         | Crypto         | DOGE/USD       | ✅      |
| 4         | Crypto         | MATIC/USD      | ❌      |
| 5         | Crypto         | ADA/USD        | ✅      |
| 6         | Crypto         | SUSHI/USD      | ❌      |
| 7         | Crypto         | AAVE/USD       | ✅      |
| 8         | Crypto         | ALGO/USD       | ✅      |
| 9         | Crypto         | BAT/USD        | ✅      |
| 10        | Crypto         | COMP/USD       | ✅      |
| 11        | Crypto         | DOT/USD        | ✅      |
| 12        | Crypto         | EOS/USD        | ❌      |
| 13        | Crypto         | LTC/USD        | ❌      |
| 14        | Crypto         | MANA/USD       | ✅      |
| 15        | Crypto         | OMG/USD        | ❌      |
| 16        | Crypto         | SNX/USD        | ❌      |
| 17        | Crypto         | UNI/USD        | ✅      |
| 18        | Crypto         | XLM/USD        | ✅      |
| 19        | Crypto         | XRP/USD        | ✅      |
| 20        | Crypto         | ZEC/USD        | ✅      |
| 21        | Forex (Major)  | EUR/USD        | ✅      |
| 22        | Forex (Major)  | USD/JPY        | ✅      |
| 23        | Forex (Major)  | GBP/USD        | ✅      |
| 24        | Forex (Major)  | USD/CHF        | ❌      |
| 25        | Forex (Major)  | AUD/USD        | ❌      |
| 26        | Forex (Major)  | USD/CAD        | ✅      |
| 27        | Forex (Major)  | NZD/USD        | ❌      |
| 28        | Forex (Major)  | EUR/CHF        | ❌      |
| 29        | Forex (Major)  | EUR/JPY        | ✅      |
| 30        | Forex (Major)  | EUR/GBP        | ❌      |
| 31        | Crypto         | LUNA/USD       | ❌      |
| 32        | Crypto         | YFI/USD        | ❌      |
| 33        | Crypto         | SOL/USD        | ✅      |
| 34        | Crypto         | XTZ/USD        | ✅      |
| 35        | Crypto         | BCH/USD        | ✅      |
| 36        | Crypto         | BNT/USD        | ❌      |
| 37        | Crypto         | CRV/USD        | ✅      |
| 38        | Crypto         | DASH/USD       | ✅      |
| 39        | Crypto         | ETC/USD        | ✅      |
| 40        | Crypto         | ICP/USD        | ✅      |
| 41        | Crypto         | MKR/USD        | ❌      |
| 42        | Crypto         | NEO/USD        | ❌      |
| 43        | Crypto         | THETA/USD      | ✅      |
| 44        | Crypto         | TRX/USD        | ✅      |
| 45        | Crypto         | ZRX/USD        | ❌      |
| 46        | Crypto         | SAND/USD       | ✅      |
| 47        | Crypto         | BNB/USD        | ✅      |
| 48        | Crypto         | AXS/USD        | ❌      |
| 49        | Crypto         | GRT/USD        | ✅      |
| 50        | Crypto         | HBAR/USD       | ✅      |
| 51        | Crypto         | XMR/USD        | ✅      |
| 52        | Crypto         | ENJ/USD        | ❌      |
| 53        | Crypto         | FTM/USD        | ❌      |
| 54        | Crypto         | FTT/USD        | ❌      |
| 55        | Crypto         | APE/USD        | ❌      |
| 56        | Crypto         | CHZ/USD        | ✅      |
| 57        | Crypto         | SHIB/USD       | ✅      |
| 58        | Stocks         | AAPL/USD       | ✅      |
| 59        | Stocks         | FB/USD         | ❌      |
| 60        | Stocks         | GOOGL/USD      | ❌      |
| 61        | Stocks         | AMZN/USD       | ❌      |
| 62        | Stocks         | MSFT/USD       | ✅      |
| 63        | Stocks         | TSLA/USD       | ❌      |
| 64        | Stocks         | SNAP/USD       | ✅      |
| 65        | Stocks         | NVDA/USD       | ✅      |
| 66        | Stocks         | V/USD          | ❌      |
| 67        | Stocks         | MA/USD         | ❌      |
| 68        | Stocks         | PFE/USD        | ❌      |
| 69        | Stocks         | KO/USD         | ❌      |
| 70        | Stocks         | DIS/USD        | ❌      |
| 71        | Stocks         | GME/USD        | ❌      |
| 72        | Stocks         | NKE/USD        | ❌      |
| 73        | Stocks         | AMD/USD        | ❌      |
| 74        | Stocks         | PYPL/USD       | ✅      |
| 75        | Stocks         | ABNB/USD       | ❌      |
| 76        | Stocks         | BA/USD         | ❌      |
| 77        | Stocks         | SBUX/USD       | ❌      |
| 78        | Stocks         | WMT/USD        | ❌      |
| 79        | Stocks         | INTC/USD       | ❌      |
| 80        | Stocks         | MCD/USD        | ✅      |
| 81        | Stocks         | META/USD       | ✅      |
| 82        | Stocks         | GOOGL\_1/USD   | ✅      |
| 83        | Stocks         | GME\_1/USD     | ✅      |
| 84        | Stocks         | AMZN\_1/USD    | ✅      |
| 85        | Stocks         | TSLA\_1/USD    | ✅      |
| 86        | Index          | SPY/USD        | ✅      |
| 87        | Index          | QQQ/USD        | ✅      |
| 88        | Index          | IWM/USD        | ✅      |
| 89        | Index          | DIA/USD        | ✅      |
| 90        | Commodity      | XAU/USD        | ✅      |
| 91        | Commodity      | XAG/USD        | ✅      |
| 92        | Forex (Exotic) | USD/CNH        | ✅      |
| 93        | Forex (Exotic) | USD/SGD        | ✅      |
| 94        | Forex (Exotic) | EUR/SEK        | ✅      |
| 95        | Forex (Exotic) | USD/KRW        | ❌      |
| 96        | Forex (Exotic) | EUR/NOK        | ❌      |
| 97        | Forex (Exotic) | USD/INR        | ❌      |
| 98        | Forex (Exotic) | USD/MXN        | ❌      |
| 99        | Forex (Exotic) | USD/TWD        | ❌      |
| 100       | Forex (Exotic) | USD/ZAR        | ✅      |
| 101       | Forex (Exotic) | USD/BRL        | ❌      |
| 102       | Crypto         | AVAX/USD       | ✅      |
| 103       | Crypto         | ATOM/USD       | ✅      |
| 104       | Crypto         | NEAR/USD       | ✅      |
| 105       | Crypto         | QNT/USD        | ✅      |
| 106       | Crypto         | IOTA/USD       | ❌      |
| 107       | Crypto         | TON/USD        | ✅      |
| 108       | Crypto         | RPL/USD        | ❌      |
| 109       | Crypto         | ARB/USD        | ✅      |
| 110       | Forex (Minor)  | EUR/AUD        | ✅      |
| 111       | Forex (Minor)  | EUR/NZD        | ❌      |
| 112       | Forex (Minor)  | EUR/CAD        | ✅      |
| 113       | Forex (Minor)  | GBP/AUD        | ❌      |
| 114       | Forex (Minor)  | GBP/NZD        | ❌      |
| 115       | Forex (Minor)  | GBP/CAD        | ✅      |
| 116       | Forex (Minor)  | GBP/CHF        | ❌      |
| 117       | Forex (Minor)  | GBP/JPY        | ✅      |
| 118       | Forex (Minor)  | AUD/NZD        | ❌      |
| 119       | Forex (Minor)  | AUD/CAD        | ✅      |
| 120       | Forex (Minor)  | AUD/CHF        | ❌      |
| 121       | Forex (Minor)  | AUD/JPY        | ✅      |
| 122       | Forex (Minor)  | NZD/CAD        | ❌      |
| 123       | Forex (Minor)  | NZD/CHF        | ❌      |
| 124       | Forex (Minor)  | NZD/JPY        | ✅      |
| 125       | Forex (Minor)  | CAD/CHF        | ❌      |
| 126       | Forex (Minor)  | CAD/JPY        | ✅      |
| 127       | Forex (Minor)  | CHF/JPY        | ❌      |
| 128       | Crypto         | LDO/USD        | ✅      |
| 129       | Crypto         | INJ/USD        | ✅      |
| 130       | Crypto         | RUNE/USD       | ❌      |
| 131       | Crypto         | CAKE/USD       | ✅      |
| 132       | Crypto         | FXS/USD        | ❌      |
| 133       | Crypto         | TWT/USD        | ✅      |
| 134       | Crypto         | PEPE/USD       | ✅      |
| 135       | Crypto         | DYDX/USD       | ❌      |
| 136       | Crypto         | GMX/USD        | ❌      |
| 137       | Crypto         | FIL/USD        | ✅      |
| 138       | Crypto         | APT/USD        | ✅      |
| 139       | Crypto         | IMX/USD        | ✅      |
| 140       | Crypto         | VET/USD        | ✅      |
| 141       | Crypto         | OP/USD         | ✅      |
| 142       | Crypto         | RNDR/USD       | ✅      |
| 143       | Crypto         | EGLD/USD       | ✅      |
| 144       | Crypto         | TIA/USD        | ✅      |
| 145       | Crypto         | STX/USD        | ✅      |
| 146       | Crypto         | FLOW/USD       | ❌      |
| 147       | Crypto         | KAVA/USD       | ❌      |
| 148       | Crypto         | GALA/USD       | ✅      |
| 149       | Crypto         | MINA/USD       | ❌      |
| 150       | Crypto         | ORDI/USD       | ❌      |
| 151       | Crypto         | ILV/USD        | ❌      |
| 152       | Crypto         | KLAY/USD       | ❌      |
| 153       | Crypto         | SUI/USD        | ✅      |
| 154       | Crypto         | BLUR/USD       | ❌      |
| 155       | Crypto         | FET/USD        | ✅      |
| 156       | Crypto         | CFX/USD        | ✅      |
| 157       | Crypto         | BEAM/USD       | ❌      |
| 158       | Crypto         | AR/USD         | ✅      |
| 159       | Crypto         | SEI/USD        | ✅      |
| 160       | Crypto         | BTT/USD        | ❌      |
| 161       | Crypto         | ROSE/USD       | ❌      |
| 162       | Crypto         | WOO/USD        | ❌      |
| 163       | Crypto         | AGIX/USD       | ❌      |
| 164       | Crypto         | ZIL/USD        | ❌      |
| 165       | Crypto         | GMT/USD        | ❌      |
| 166       | Crypto         | ASTR/USD       | ❌      |
| 167       | Crypto         | 1INCH/USD      | ✅      |
| 168       | Crypto         | FLOKI/USD      | ✅      |
| 169       | Crypto         | QTUM/USD       | ❌      |
| 170       | Crypto         | OCEAN/USD      | ❌      |
| 171       | Crypto         | WLD/USD        | ✅      |
| 172       | Crypto         | MASK/USD       | ❌      |
| 173       | Crypto         | CELO/USD       | ❌      |
| 174       | Crypto         | LRC/USD        | ❌      |
| 175       | Crypto         | ENS/USD        | ✅      |
| 176       | Crypto         | MEME/USD       | ❌      |
| 177       | Crypto         | ANKR/USD       | ❌      |
| 178       | Crypto         | IOTX/USD       | ❌      |
| 179       | Crypto         | ICX/USD        | ❌      |
| 180       | Crypto         | KSM/USD        | ❌      |
| 181       | Crypto         | RVN/USD        | ❌      |
| 182       | Crypto         | ANT/USD        | ❌      |
| 183       | Crypto         | WAVES/USD      | ❌      |
| 184       | Crypto         | SKL/USD        | ❌      |
| 185       | Crypto         | SUPER/USD      | ❌      |
| 186       | Crypto         | BAL/USD        | ❌      |
| 187       | Commodity      | WTI/USD        | ✅      |
| 188       | Commodity      | XPT/USD        | ✅      |
| 189       | Commodity      | XPD/USD        | ✅      |
| 190       | Commodity      | HG/USD         | ✅      |
| 191       | Crypto         | JUP/USD        | ✅      |
| 192       | Crypto         | MANTA/USD      | ❌      |
| 193       | Crypto         | BONK/USD       | ✅      |
| 194       | Crypto         | PENDLE/USD     | ✅      |
| 195       | Crypto         | OSMO/USD       | ❌      |
| 196       | Crypto         | ALT/USD        | ❌      |
| 197       | Crypto         | UMA/USD        | ❌      |
| 198       | Crypto         | MAGIC/USD      | ❌      |
| 199       | Crypto         | API3/USD       | ❌      |
| 200       | Crypto         | STRK/USD       | ✅      |
| 201       | Crypto         | DYM/USD        | ❌      |
| 202       | Crypto         | NTRN/USD       | ❌      |
| 203       | Crypto         | PYTH/USD       | ✅      |
| 204       | Crypto         | SC/USD         | ❌      |
| 205       | Crypto         | WIF/USD        | ✅      |
| 206       | Crypto         | PIXEL/USD      | ❌      |
| 207       | Crypto         | JTO/USD        | ❌      |
| 208       | Crypto         | MAVIA/USD      | ❌      |
| 209       | Crypto         | MYRO/USD       | ❌      |
| 210       | Crypto         | STG/USD        | ❌      |
| 211       | Crypto         | BOME/USD       | ❌      |
| 212       | Crypto         | ETHFI/USD      | ✅      |
| 213       | Crypto         | METIS/USD      | ❌      |
| 214       | Crypto         | AEVO/USD       | ❌      |
| 215       | Crypto         | ONDO/USD       | ✅      |
| 216       | Crypto         | MNT/USD        | ✅      |
| 217       | Crypto         | KAS/USD        | ✅      |
| 218       | Crypto         | RONIN/USD      | ❌      |
| 219       | Crypto         | ENA/USD        | ✅      |
| 220       | Crypto         | W/USD          | ❌      |
| 221       | Crypto         | ZEUS/USD       | ❌      |
| 222       | Crypto         | TNSR/USD       | ❌      |
| 223       | Crypto         | TAO/USD        | ✅      |
| 224       | Crypto         | OMNI/USD       | ❌      |
| 225       | Crypto         | PRCL/USD       | ❌      |
| 226       | Crypto         | MERL/USD       | ❌      |
| 227       | Crypto         | SAFE/USD       | ❌      |
| 228       | Crypto         | SAGA/USD       | ❌      |
| 229       | Crypto         | LL/USD         | ❌      |
| 230       | Crypto         | MSN/USD        | ❌      |
| 231       | Crypto         | REZ/USD        | ❌      |
| 232       | Crypto         | NOT/USD        | ❌      |
| 233       | Crypto         | IO/USD         | ❌      |
| 234       | Crypto         | BRETT/USD      | ❌      |
| 235       | Crypto         | ATH/USD        | ❌      |
| 236       | Crypto         | ZRO/USD        | ✅      |
| 237       | Crypto         | ZK/USD         | ✅      |
| 238       | Crypto         | LISTA/USD      | ❌      |
| 239       | Crypto         | BLAST/USD      | ❌      |
| 240       | Crypto         | RATS/USD       | ❌      |
| 241       | Crypto         | BNX/USD        | ❌      |
| 242       | Crypto         | PEOPLE/USD     | ❌      |
| 243       | Crypto         | TURBO/USD      | ❌      |
| 244       | Crypto         | SATS/USD       | ❌      |
| 245       | Crypto         | POPCAT/USD     | ❌      |
| 246       | Crypto         | MOG/USD        | ❌      |
| 247       | Crypto         | OM/USD         | ❌      |
| 248       | Crypto         | CORE/USD       | ❌      |
| 249       | Crypto         | JASMY/USD      | ✅      |
| 250       | Crypto         | DAR/USD        | ❌      |
| 251       | Crypto         | MEW/USD        | ❌      |
| 252       | Crypto         | DEGEN/USD      | ❌      |
| 253       | Crypto         | SLERF/USD      | ❌      |
| 254       | Crypto         | UXLINK/USD     | ❌      |
| 255       | Crypto         | AVAIL/USD      | ❌      |
| 256       | Crypto         | BANANA/USD     | ❌      |
| 257       | Crypto         | RARE/USD       | ❌      |
| 258       | Crypto         | SYS/USD        | ❌      |
| 259       | Crypto         | NMR/USD        | ❌      |
| 260       | Crypto         | RSR/USD        | ❌      |
| 261       | Crypto         | SYN/USD        | ❌      |
| 262       | Crypto         | AUCTION/USD    | ❌      |
| 263       | Crypto         | ALICE/USD      | ❌      |
| 264       | Crypto         | SUN/USD        | ✅      |
| 265       | Crypto         | TRB/USD        | ❌      |
| 266       | Crypto         | DOGS/USD       | ❌      |
| 267       | Crypto         | SSV/USD        | ❌      |
| 268       | Crypto         | PONKE/USD      | ❌      |
| 269       | Crypto         | POL/USD        | ✅      |
| 270       | Crypto         | RDNT/USD       | ❌      |
| 271       | Crypto         | FLUX/USD       | ❌      |
| 272       | Crypto         | NEIRO/USD      | ❌      |
| 273       | Crypto         | SUNDOG/USD     | ❌      |
| 274       | Crypto         | CAT/USD        | ❌      |
| 275       | Crypto         | BABYDOGE/USD   | ❌      |
| 276       | Crypto         | REEF/USD       | ❌      |
| 277       | Crypto         | CKB/USD        | ❌      |
| 278       | Crypto         | CATI/USD       | ❌      |
| 279       | Crypto         | LOOM/USD       | ❌      |
| 280       | Crypto         | ZETA/USD       | ❌      |
| 281       | Crypto         | HMSTR/USD      | ❌      |
| 282       | Crypto         | EIGEN/USD      | ✅      |
| 283       | Crypto         | POLYX/USD      | ❌      |
| 284       | Crypto         | MOODENG/USD    | ❌      |
| 285       | Crypto         | MOTHER/USD     | ❌      |
| 286       | Crypto         | AERO/USD       | ✅      |
| 287       | Crypto         | CVC/USD        | ❌      |
| 288       | Crypto         | NEIROCTO/USD   | ❌      |
| 289       | Crypto         | ARK/USD        | ❌      |
| 290       | Crypto         | NPC/USD        | ❌      |
| 291       | Crypto         | ORBS/USD       | ❌      |
| 292       | Crypto         | APU/USD        | ❌      |
| 293       | Crypto         | BSV/USD        | ✅      |
| 294       | Crypto         | HIPPO/USD      | ❌      |
| 295       | Crypto         | GOAT/USD       | ❌      |
| 296       | Crypto         | DOG/USD        | ❌      |
| 297       | Crypto         | HOT/USD        | ❌      |
| 298       | Crypto         | STORJ/USD      | ❌      |
| 299       | Crypto         | RAY/USD        | ✅      |
| 300       | Crypto         | BTCDEGEN/USD   | ✅      |
| 301       | Crypto         | PNUT/USD       | ❌      |
| 302       | Crypto         | ACT/USD        | ❌      |
| 303       | Crypto         | GRASS/USD      | ❌      |
| 304       | Crypto         | ZEN/USD        | ✅      |
| 305       | Crypto         | LUMIA/USD      | ❌      |
| 306       | Crypto         | ALPH/USD       | ❌      |
| 307       | Crypto         | VIRTUAL/USD    | ✅      |
| 308       | Crypto         | SPX/USD        | ❌      |
| 309       | Crypto         | ACX/USD        | ❌      |
| 310       | Crypto         | CHILLGUY/USD   | ❌      |
| 311       | Crypto         | CHEX/USD       | ❌      |
| 312       | Crypto         | BITCOIN/USD    | ❌      |
| 313       | Crypto         | ETHDEGEN/USD   | ✅      |
| 314       | Crypto         | SOLDEGEN/USD   | ✅      |
| 315       | Crypto         | MOVE/USD       | ❌      |
| 316       | Crypto         | ME/USD         | ❌      |
| 317       | Crypto         | COW/USD        | ❌      |
| 318       | Crypto         | AVA/USD        | ❌      |
| 319       | Crypto         | USUAL/USD      | ❌      |
| 320       | Crypto         | PENGU/USD      | ✅      |
| 321       | Crypto         | FARTCOIN/USD   | ✅      |
| 322       | Crypto         | ZEREBRO/USD    | ❌      |
| 323       | Crypto         | AI16Z/USD      | ❌      |
| 324       | Crypto         | AIXBT/USD      | ❌      |
| 325       | Crypto         | BIO/USD        | ❌      |
| 326       | Crypto         | XRPDEGEN/USD   | ❌      |
| 327       | Crypto         | BNBDEGEN/USD   | ✅      |
| 328       | Crypto         | TRUMP/USD      | ✅      |
| 329       | Crypto         | MELANIA/USD    | ✅      |
| 330       | Crypto         | MODE/USD       | ❌      |
| 331       | Crypto         | HYPE/USD       | ✅      |
| 332       | Crypto         | S/USD          | ✅      |
| 333       | Crypto         | ARC/USD        | ❌      |
| 334       | Crypto         | ARKM/USD       | ❌      |
| 335       | Crypto         | GRIFFAIN/USD   | ❌      |
| 336       | Crypto         | SWARMS/USD     | ❌      |
| 337       | Crypto         | ANIME/USD      | ❌      |
| 338       | Crypto         | PLUME/USD      | ❌      |
| 339       | Crypto         | VVV/USD        | ✅      |
| 340       | Crypto         | VINE/USD       | ❌      |
| 341       | Crypto         | TOSHI/USD      | ❌      |
| 342       | Crypto         | BERA/USD       | ❌      |
| 343       | Crypto         | LAYER/USD      | ❌      |
| 344       | Crypto         | CHEEMS/USD     | ❌      |
| 345       | Crypto         | SOLV/USD       | ❌      |
| 346       | Crypto         | TST/USD        | ❌      |
| 347       | Crypto         | IP/USD         | ❌      |
| 348       | Crypto         | KAITO/USD      | ❌      |
| 349       | Crypto         | ELX/USD        | ❌      |
| 350       | Crypto         | PI/USD         | ❌      |
| 351       | Crypto         | SHELL/USD      | ❌      |
| 352       | Crypto         | BMT/USD        | ❌      |
| 353       | Crypto         | BROCCOLI/USD   | ❌      |
| 354       | Crypto         | TUT/USD        | ❌      |
| 355       | Crypto         | GPS/USD        | ❌      |
| 356       | Crypto         | RED/USD        | ❌      |
| 357       | Crypto         | MUBARAK/USD    | ❌      |
| 358       | Crypto         | FORM/USD       | ❌      |
| 359       | Crypto         | WAL/USD        | ❌      |
| 360       | Crypto         | NIL/USD        | ❌      |
| 361       | Crypto         | PARTI/USD      | ❌      |
| 362       | Crypto         | SIREN/USD      | ❌      |
| 363       | Crypto         | BANANAS31/USD  | ✅      |
| 364       | Crypto         | HYPER/USD      | ❌      |
| 365       | Crypto         | PROMPT/USD     | ❌      |
| 366       | Crypto         | RFC/USD        | ❌      |
| 367       | Crypto         | WCT/USD        | ❌      |
| 368       | Crypto         | BIGTIME/USD    | ❌      |
| 369       | Crypto         | BABY/USD       | ❌      |
| 370       | Crypto         | COOKIE/USD     | ❌      |
| 371       | Crypto         | KMNO/USD       | ❌      |
| 372       | Crypto         | INIT/USD       | ❌      |
| 373       | Crypto         | SYRUP/USD      | ✅      |
| 374       | Crypto         | SIGN/USD       | ❌      |
| 375       | Crypto         | ZORA/USD       | ❌      |
| 376       | Stocks         | COIN/USD       | ✅      |
| 377       | Stocks         | HOOD/USD       | ✅      |
| 378       | Stocks         | MSTR/USD       | ✅      |
| 379       | Stocks         | NFLX/USD       | ❌      |
| 380       | Crypto         | LAUNCHCOIN/USD | ❌      |
| 381       | Crypto         | NXPC/USD       | ❌      |
| 382       | Crypto         | SOPH/USD       | ❌      |
| 383       | Crypto         | LPT/USD        | ✅      |
| 384       | Crypto         | BVIV/USD       | ✅      |
| 385       | Crypto         | EVIV/USD       | ✅      |
| 386       | Stocks         | CRCL/USD       | ✅      |
| 387       | Crypto         | RESOLV/USD     | ❌      |
| 388       | Crypto         | SQD/USD        | ❌      |
| 389       | Crypto         | TAIKO/USD      | ❌      |
| 390       | Crypto         | HOME/USD       | ❌      |
| 391       | Crypto         | B/USD          | ✅      |
| 392       | Crypto         | HUMA/USD       | ❌      |
| 393       | Stocks         | SBET/USD       | ❌      |
| 394       | Stocks         | PLTR/USD       | ✅      |
| 395       | Stocks         | BIDU/USD       | ❌      |
| 396       | Stocks         | ROKU/USD       | ❌      |
| 397       | Stocks         | LMT/USD        | ✅      |
| 398       | Stocks         | RIOT/USD       | ✅      |
| 399       | Stocks         | MARA/USD       | ✅      |
| 400       | Crypto         | LOKA/USD       | ❌      |
| 401       | Crypto         | STO/USD        | ❌      |
| 402       | Crypto         | FUN/USD        | ❌      |
| 403       | Crypto         | KNC/USD        | ❌      |
| 404       | Crypto         | H/USD          | ✅      |
| 405       | Crypto         | ICNT/USD       | ❌      |
| 406       | Crypto         | NEWT/USD       | ❌      |
| 407       | Crypto         | PUMP/USD       | ✅      |
| 408       | Crypto         | SAROS/USD      | ❌      |
| 409       | Crypto         | SPK/USD        | ❌      |
| 410       | Crypto         | ERA/USD        | ❌      |
| 411       | Crypto         | BGSC/USD       | ❌      |
| 412       | Crypto         | TAG/USD        | ❌      |
| 413       | Crypto         | WLFI/USD       | ✅      |
| 414       | Crypto         | ASTER/USD      | ✅      |
| 415       | Crypto         | OKB/USD        | ✅      |
| 416       | Crypto         | CRO/USD        | ✅      |
| 417       | Crypto         | SKY/USD        | ✅      |
| 418       | Crypto         | XPL/USD        | ✅      |
| 419       | Crypto         | AVNT/USD       | ❌      |
| 420       | Crypto         | APEX/USD       | ❌      |
| 421       | Crypto         | ORDER/USD      | ❌      |
| 422       | Crypto         | DRIFT/USD      | ❌      |
| 423       | Crypto         | MYX/USD        | ❌      |
| 424       | Crypto         | NOM/USD        | ❌      |
| 425       | Crypto         | FLUID/USD      | ✅      |
| 426       | Crypto         | LQTY/USD       | ❌      |
| 427       | Crypto         | L3/USD         | ❌      |
| 428       | Crypto         | CAMP/USD       | ❌      |
| 429       | Crypto         | SOMI/USD       | ❌      |
| 430       | Crypto         | HEMI/USD       | ❌      |
| 431       | Crypto         | FF/USD         | ❌      |
| 432       | Crypto         | USELESS/USD    | ❌      |
| 433       | Crypto         | MON/USD        | ✅      |
| 434       | Crypto         | MET/USD        | ❌      |
| 435       | Crypto         | TURTLE/USD     | ❌      |
| 436       | Index          | SPX500/USD     | ❌      |
| 437       | Index          | NAS100/USD     | ❌      |
| 438       | Index          | USA30/USD      | ❌      |
| 439       | Stocks         | NFLX\_1/USD    | ✅      |
| 440       | Crypto         | STABLE/USD     | ❌      |
| 441       | Crypto         | VOOI/USD       | ❌      |
| 442       | Crypto         | LIT/USD        | ✅      |
| 443       | Crypto         | DUSK/USD       | ❌      |
| 444       | Crypto         | SCRT/USD       | ❌      |
| 445       | Crypto         | DCR/USD        | ✅      |
| 446       | Index          | GDX/USD        | ✅      |
| 447       | Index          | URA/USD        | ✅      |
| 448       | Stocks         | WPM/USD        | ✅      |
| 449       | Commodity      | NATGAS/USD     | ❌      |
| 450       | Commodity      | BRENT/USD      | ❌      |
| 451       | Index          | URNM/USD       | ✅      |
| 452       | Crypto         | HYPEDEGEN/USD  | ✅      |
| 453       | Crypto         | MEGA/USD       | ✅      |


# Old Pair List

This is a list of gTrade trading pairs, their relevant pairIndex, and the asset class. \
\
The pairIndex:

* Is useful in the case of needing to interact with the contracts directly.
* Reflects the chronological order the asset was added to gTrade.
* Includes pairs that are no longer listed, but kept for technical reasons.

<table><thead><tr><th width="161.3695407838375">pairIndex</th><th width="150">Asset Class</th><th>Asset</th><th data-type="checkbox">Active</th></tr></thead><tbody><tr><td>0</td><td>Crypto</td><td>BTC/USD</td><td>true</td></tr><tr><td>1</td><td>Crypto</td><td>ETH/USD</td><td>true</td></tr><tr><td>2</td><td>Crypto</td><td>LINK/USD</td><td>true</td></tr><tr><td>3</td><td>Crypto</td><td>DOGE/USD</td><td>true</td></tr><tr><td>4</td><td>Crypto</td><td>MATIC/USD</td><td>true</td></tr><tr><td>5</td><td>Crypto</td><td>ADA/USD</td><td>true</td></tr><tr><td>6</td><td>Crypto</td><td>SUSHI/USD</td><td>false</td></tr><tr><td>7</td><td>Crypto</td><td>AAVE/USD</td><td>true</td></tr><tr><td>8</td><td>Crypto</td><td>ALGO/USD</td><td>true</td></tr><tr><td>9</td><td>Crypto</td><td>BAT/USD</td><td>true</td></tr><tr><td>10</td><td>Crypto</td><td>COMP/USD</td><td>true</td></tr><tr><td>11</td><td>Crypto</td><td>DOT/USD</td><td>true</td></tr><tr><td>12</td><td>Crypto</td><td>EOS/USD</td><td>true</td></tr><tr><td>13</td><td>Crypto</td><td>LTC/USD</td><td>true</td></tr><tr><td>14</td><td>Crypto</td><td>MANA/USD</td><td>true</td></tr><tr><td>15</td><td>Crypto</td><td>OMG/USD</td><td>false</td></tr><tr><td>16</td><td>Crypto</td><td>SNX/USD</td><td>true</td></tr><tr><td>17</td><td>Crypto</td><td>UNI/USD</td><td>true</td></tr><tr><td>18</td><td>Crypto</td><td>XLM/USD</td><td>true</td></tr><tr><td>19</td><td>Crypto</td><td>XRP/USD</td><td>true</td></tr><tr><td>20</td><td>Crypto</td><td>ZEC/USD</td><td>true</td></tr><tr><td>21</td><td>Forex (major)</td><td>EUR/USD</td><td>true</td></tr><tr><td>22</td><td>Forex (major)</td><td>USD/JPY</td><td>true</td></tr><tr><td>23</td><td>Forex (major)</td><td>GBP/USD</td><td>true</td></tr><tr><td>24</td><td>Forex (major)</td><td>USD/CHF</td><td>false</td></tr><tr><td>25</td><td>Forex (major)</td><td>AUD/USD</td><td>false</td></tr><tr><td>26</td><td>Forex (major)</td><td>USD/CAD</td><td>true</td></tr><tr><td>27</td><td>Forex (major)</td><td>NZD/USD</td><td>false</td></tr><tr><td>28</td><td>Forex (minor)</td><td>EUR/CHF</td><td>false</td></tr><tr><td>29</td><td>Forex (minor)</td><td>EUR/JPY</td><td>true</td></tr><tr><td>30</td><td>Forex (minor)</td><td>EUR/GBP</td><td>false</td></tr><tr><td>31</td><td>Crypto</td><td>LUNA/USD</td><td>false</td></tr><tr><td>32</td><td>Crypto</td><td>YFI/USD</td><td>true</td></tr><tr><td>33</td><td>Crypto</td><td>SOL/USD</td><td>true</td></tr><tr><td>34</td><td>Crypto</td><td>XTZ/USD</td><td>true</td></tr><tr><td>35</td><td>Crypto</td><td>BCH/USD</td><td>true</td></tr><tr><td>36</td><td>Crypto</td><td>BNT/USD</td><td>false</td></tr><tr><td>37</td><td>Crypto</td><td>CRV/USD</td><td>true</td></tr><tr><td>38</td><td>Crypto</td><td>DASH/USD</td><td>true</td></tr><tr><td>39</td><td>Crypto</td><td>ETC/USD</td><td>true</td></tr><tr><td>40</td><td>Crypto</td><td>ICP/USD</td><td>true</td></tr><tr><td>41</td><td>Crypto</td><td>MKR/USD</td><td>true</td></tr><tr><td>42</td><td>Crypto</td><td>NEO/USD</td><td>true</td></tr><tr><td>43</td><td>Crypto</td><td>THETA/USD</td><td>true</td></tr><tr><td>44</td><td>Crypto</td><td>TRX/USD</td><td>true</td></tr><tr><td>45</td><td>Crypto</td><td>ZRX/USD</td><td>true</td></tr><tr><td>46</td><td>Crypto</td><td>SAND/USD</td><td>true</td></tr><tr><td>47</td><td>Crypto</td><td>BNB/USD</td><td>true</td></tr><tr><td>48</td><td>Crypto</td><td>AXS/USD</td><td>false</td></tr><tr><td>49</td><td>Crypto</td><td>GRT/USD</td><td>true</td></tr><tr><td>50</td><td>Crypto</td><td>HBAR/USD</td><td>true</td></tr><tr><td>51</td><td>Crypto</td><td>XMR/USD</td><td>false</td></tr><tr><td>52</td><td>Crypto</td><td>ENJ/USD</td><td>false</td></tr><tr><td>53</td><td>Crypto</td><td>FTM/USD</td><td>true</td></tr><tr><td>54</td><td>Crypto</td><td>FTT/USD</td><td>false</td></tr><tr><td>55</td><td>Crypto</td><td>APE/USD</td><td>true</td></tr><tr><td>56</td><td>Crypto</td><td>CHZ/USD</td><td>true</td></tr><tr><td>57</td><td>Crypto</td><td>SHIB/USD</td><td>true</td></tr><tr><td>58</td><td>Stock</td><td>AAPL/USD</td><td>false</td></tr><tr><td>59</td><td>Stock</td><td>FB/USD</td><td>false</td></tr><tr><td>60</td><td>Stock</td><td>GOOGL/USD</td><td>false</td></tr><tr><td>61</td><td>Stock</td><td>AMZN/USD</td><td>false</td></tr><tr><td>62</td><td>Stock</td><td>MSFT/USD</td><td>false</td></tr><tr><td>63</td><td>Stock</td><td>TSLA/USD</td><td>false</td></tr><tr><td>64</td><td>Stock</td><td>SNAP/USD</td><td>false</td></tr><tr><td>65</td><td>Stock</td><td>NVDA/USD</td><td>false</td></tr><tr><td>66</td><td>Stock</td><td>V/USD</td><td>false</td></tr><tr><td>67</td><td>Stock</td><td>MA/USD</td><td>false</td></tr><tr><td>68</td><td>Stock</td><td>PFE/USD</td><td>false</td></tr><tr><td>69</td><td>Stock</td><td>KO/USD</td><td>false</td></tr><tr><td>70</td><td>Stock</td><td>DIS/USD</td><td>false</td></tr><tr><td>71</td><td>Stock</td><td>GME/USD</td><td>false</td></tr><tr><td>72</td><td>Stock</td><td>NKE/USD</td><td>false</td></tr><tr><td>73</td><td>Stock</td><td>AMD/USD</td><td>false</td></tr><tr><td>74</td><td>Stock</td><td>PYPL/USD</td><td>false</td></tr><tr><td>75</td><td>Stock</td><td>ABNB/USD</td><td>false</td></tr><tr><td>76</td><td>Stock</td><td>BA/USD</td><td>false</td></tr><tr><td>77</td><td>Stock</td><td>SBUX/USD</td><td>false</td></tr><tr><td>78</td><td>Stock</td><td>WMT/USD</td><td>false</td></tr><tr><td>79</td><td>Stock</td><td>INTC/USD</td><td>false</td></tr><tr><td>80</td><td>Stock</td><td>MCD/USD</td><td>false</td></tr><tr><td>81</td><td>Stock</td><td>META/USD</td><td>false</td></tr><tr><td>82</td><td>Stock</td><td>GOOGL_1/USD</td><td>false</td></tr><tr><td>83</td><td>Stock</td><td>GME_1/USD</td><td>false</td></tr><tr><td>84</td><td>Stock</td><td>AMZN_1/USD</td><td>false</td></tr><tr><td>85</td><td>Stock</td><td>TSLA_1/USD</td><td>false</td></tr><tr><td>86</td><td>Index</td><td>SPY/USD</td><td>false</td></tr><tr><td>87</td><td>Index</td><td>QQQ/USD</td><td>false</td></tr><tr><td>88</td><td>Index</td><td>IWM/USD</td><td>false</td></tr><tr><td>89</td><td>Index</td><td>DIA/USD</td><td>false</td></tr><tr><td>90</td><td>Commodity</td><td>XAU/USD</td><td>false</td></tr><tr><td>91</td><td>Commodity</td><td>XAG/USD</td><td>false</td></tr><tr><td>92</td><td>Forex (exotic)</td><td>USD/CNH</td><td>true</td></tr><tr><td>93</td><td>Forex (exotic)</td><td>USD/SGD</td><td>true</td></tr><tr><td>94</td><td>Forex (exotic)</td><td>EUR/SEK</td><td>false</td></tr><tr><td>95</td><td>Forex (exotic)</td><td>USD/KRW</td><td>false</td></tr><tr><td>96</td><td>Forex (exotic)</td><td>EUR/NOK</td><td>false</td></tr><tr><td>97</td><td>Forex (exotic)</td><td>USD/INR</td><td>false</td></tr><tr><td>98</td><td>Forex (exotic)</td><td>USD/MXN</td><td>false</td></tr><tr><td>99</td><td>Forex (exotic)</td><td>USD/TWD</td><td>false</td></tr><tr><td>100</td><td>Forex (exotic)</td><td>USD/ZAR</td><td>true</td></tr><tr><td>101</td><td>Forex (exotic)</td><td>USD/BRL</td><td>false</td></tr><tr><td>102</td><td>Crypto</td><td>AVAX/USD</td><td>true</td></tr><tr><td>103</td><td>Crypto</td><td>ATOM/USD</td><td>true</td></tr><tr><td>104</td><td>Crypto</td><td>NEAR/USD</td><td>true</td></tr><tr><td>105</td><td>Crypto</td><td>QNT/USD</td><td>true</td></tr><tr><td>106</td><td>Crypto</td><td>IOTA/USD</td><td>false</td></tr><tr><td>107</td><td>Crypto</td><td>TON/USD</td><td>true</td></tr><tr><td>108</td><td>Crypto</td><td>RPL/USD</td><td>true</td></tr><tr><td>109</td><td>Crypto</td><td>ARB/USD</td><td>true</td></tr><tr><td>110</td><td>Forex (minor)</td><td>EUR/AUD</td><td>true</td></tr><tr><td>111</td><td>Forex (minor)</td><td>EUR/NZD</td><td>false</td></tr><tr><td>112</td><td>Forex (minor)</td><td>EUR/CAD</td><td>true</td></tr><tr><td>113</td><td>Forex (minor)</td><td>GBP/AUD</td><td>true</td></tr><tr><td>114</td><td>Forex (minor)</td><td>GBP/NZD</td><td>false</td></tr><tr><td>115</td><td>Forex (minor)</td><td>GBP/CAD</td><td>true</td></tr><tr><td>116</td><td>Forex (minor)</td><td>GBP/CHF</td><td>true</td></tr><tr><td>117</td><td>Forex (minor)</td><td>GBP/JPY</td><td>true</td></tr><tr><td>118</td><td>Forex (minor)</td><td>AUD/NZD</td><td>true</td></tr><tr><td>119</td><td>Forex (minor)</td><td>AUD/CAD</td><td>true</td></tr><tr><td>120</td><td>Forex (minor)</td><td>AUD/CHF</td><td>false</td></tr><tr><td>121</td><td>Forex (minor)</td><td>AUD/JPY</td><td>true</td></tr><tr><td>122</td><td>Forex (minor)</td><td>NZD/CAD</td><td>false</td></tr><tr><td>123</td><td>Forex (minor)</td><td>NZD/CHF</td><td>false</td></tr><tr><td>124</td><td>Forex (minor)</td><td>NZD/JPY</td><td>true</td></tr><tr><td>125</td><td>Forex (minor)</td><td>CAD/CHF</td><td>false</td></tr><tr><td>126</td><td>Forex (minor)</td><td>CAD/JPY</td><td>true</td></tr><tr><td>127</td><td>Forex (minor)</td><td>CHF/JPY</td><td>true</td></tr><tr><td>128</td><td>Crypto</td><td>LDO/USD</td><td>true</td></tr><tr><td>129</td><td>Crypto</td><td>INJ/USD</td><td>true</td></tr><tr><td>130</td><td>Crypto</td><td>RUNE/USD</td><td>true</td></tr><tr><td>131</td><td>Crypto</td><td>CAKE/USD</td><td>true</td></tr><tr><td>132</td><td>Crypto</td><td>FXS/USD</td><td>true</td></tr><tr><td>133</td><td>Crypto</td><td>TWT/USD</td><td>true</td></tr><tr><td>134</td><td>Crypto</td><td>PEPE/USD</td><td>true</td></tr><tr><td>135</td><td>Crypto</td><td>DYDX/USD</td><td>true</td></tr><tr><td>136</td><td>Crypto</td><td>GMX/USD</td><td>true</td></tr><tr><td>137</td><td>Crypto</td><td>FIL/USD</td><td>true</td></tr><tr><td>138</td><td>Crypto</td><td>APT/USD</td><td>true</td></tr><tr><td>139</td><td>Crypto</td><td>IMX/USD</td><td>true</td></tr><tr><td>140</td><td>Crypto</td><td>VET/USD</td><td>true</td></tr><tr><td>141</td><td>Crypto</td><td>OP/USD</td><td>true</td></tr><tr><td>142</td><td>Crypto</td><td>RNDR/USD</td><td>true</td></tr><tr><td>143</td><td>Crypto</td><td>EGLD/USD</td><td>true</td></tr><tr><td>144</td><td>Crypto</td><td>TIA/USD</td><td>true</td></tr><tr><td>145</td><td>Crypto</td><td>STX/USD</td><td>true</td></tr><tr><td>146</td><td>Crypto</td><td>FLOW/USD</td><td>true</td></tr><tr><td>147</td><td>Crypto</td><td>KAVA/USD</td><td>false</td></tr><tr><td>148</td><td>Crypto</td><td>GALA/USD</td><td>true</td></tr><tr><td>149</td><td>Crypto</td><td>MINA/USD</td><td>true</td></tr><tr><td>150</td><td>Crypto</td><td>ORDI/USD</td><td>true</td></tr><tr><td>151</td><td>Crypto</td><td>ILV/USD</td><td>true</td></tr><tr><td>152</td><td>Crypto</td><td>KLAY/USD</td><td>true</td></tr><tr><td>153</td><td>Crypto</td><td>SUI/USD</td><td>true</td></tr><tr><td>154</td><td>Crypto</td><td>BLUR/USD</td><td>true</td></tr><tr><td>155</td><td>Crypto</td><td>FET/USD</td><td>true</td></tr><tr><td>156</td><td>Crypto</td><td>CFX/USD</td><td>true</td></tr><tr><td>157</td><td>Crypto</td><td>BEAM/USD</td><td>true</td></tr><tr><td>158</td><td>Crypto</td><td>AR/USD</td><td>true</td></tr><tr><td>159</td><td>Crypto</td><td>SEI/USD</td><td>true</td></tr><tr><td>160</td><td>Crypto</td><td>BTT/USD</td><td>false</td></tr><tr><td>161</td><td>Crypto</td><td>ROSE/USD</td><td>true</td></tr><tr><td>162</td><td>Crypto</td><td>WOO/USD</td><td>true</td></tr><tr><td>163</td><td>Crypto</td><td>AGIX/USD</td><td>false</td></tr><tr><td>164</td><td>Crypto</td><td>ZIL/USD</td><td>true</td></tr><tr><td>165</td><td>Crypto</td><td>GMT/USD</td><td>true</td></tr><tr><td>166</td><td>Crypto</td><td>ASTR/USD</td><td>true</td></tr><tr><td>167</td><td>Crypto</td><td>1INCH/USD</td><td>true</td></tr><tr><td>168</td><td>Crypto</td><td>FLOKI/USD</td><td>true</td></tr><tr><td>169</td><td>Crypto</td><td>QTUM/USD</td><td>true</td></tr><tr><td>170</td><td>Crypto</td><td>OCEAN/USD</td><td>false</td></tr><tr><td>171</td><td>Crypto</td><td>WLD/USD</td><td>true</td></tr><tr><td>172</td><td>Crypto</td><td>MASK/USD</td><td>true</td></tr><tr><td>173</td><td>Crypto</td><td>CELO/USD</td><td>true</td></tr><tr><td>174</td><td>Crypto</td><td>LRC/USD</td><td>true</td></tr><tr><td>175</td><td>Crypto</td><td>ENS/USD</td><td>true</td></tr><tr><td>176</td><td>Crypto</td><td>MEME/USD</td><td>true</td></tr><tr><td>177</td><td>Crypto</td><td>ANKR/USD</td><td>true</td></tr><tr><td>178</td><td>Crypto</td><td>IOTX/USD</td><td>true</td></tr><tr><td>179</td><td>Crypto</td><td>ICX/USD</td><td>false</td></tr><tr><td>180</td><td>Crypto</td><td>KSM/USD</td><td>true</td></tr><tr><td>181</td><td>Crypto</td><td>RVN/USD</td><td>true</td></tr><tr><td>182</td><td>Crypto</td><td>ANT/USD</td><td>false</td></tr><tr><td>183</td><td>Crypto</td><td>WAVES/USD</td><td>false</td></tr><tr><td>184</td><td>Crypto</td><td>SKL/USD</td><td>true</td></tr><tr><td>185</td><td>Crypto</td><td>SUPER/USD</td><td>true</td></tr><tr><td>186</td><td>Crypto</td><td>BAL/USD</td><td>true</td></tr><tr><td>187</td><td>Commodity</td><td>WTI/USD</td><td>false</td></tr><tr><td>188</td><td>Commodity</td><td>XPT/USD</td><td>false</td></tr><tr><td>189</td><td>Commodity</td><td>XPD/USD</td><td>false</td></tr><tr><td>190</td><td>Commodity</td><td>HG/USD</td><td>false</td></tr><tr><td>191</td><td>Crypto</td><td>JUP/USD</td><td>true</td></tr><tr><td>192</td><td>Crypto</td><td>MANTA/USD</td><td>true</td></tr><tr><td>193</td><td>Crypto</td><td>BONK/USD</td><td>true</td></tr><tr><td>194</td><td>Crypto</td><td>PENDLE/USD</td><td>true</td></tr><tr><td>195</td><td>Crypto</td><td>OSMO/USD</td><td>true</td></tr><tr><td>196</td><td>Crypto</td><td>ALT/USD</td><td>true</td></tr><tr><td>197</td><td>Crypto</td><td>UMA/USD</td><td>true</td></tr><tr><td>198</td><td>Crypto</td><td>MAGIC/USD</td><td>true</td></tr><tr><td>199</td><td>Crypto</td><td>API3/USD</td><td>true</td></tr><tr><td>200</td><td>Crypto</td><td>STRK/USD</td><td>true</td></tr><tr><td>201</td><td>Crypto</td><td>DYM/USD</td><td>true</td></tr><tr><td>202</td><td>Crypto</td><td>NTRN/USD</td><td>true</td></tr><tr><td>203</td><td>Crypto</td><td>PYTH/USD</td><td>true</td></tr><tr><td>204</td><td>Crypto</td><td>SC/USD</td><td>true</td></tr><tr><td>205</td><td>Crypto</td><td>WIF/USD</td><td>true</td></tr><tr><td>206</td><td>Crypto</td><td>PIXEL/USD</td><td>true</td></tr><tr><td>207</td><td>Crypto</td><td>JTO/USD</td><td>true</td></tr><tr><td>208</td><td>Crypto</td><td>MAVIA/USD</td><td>true</td></tr><tr><td>209</td><td>Crypto</td><td>MYRO/USD</td><td>true</td></tr><tr><td>210</td><td>Crypto</td><td>STG/USD</td><td>true</td></tr><tr><td>211</td><td>Crypto</td><td>BOME/USD</td><td>true</td></tr><tr><td>212</td><td>Crypto</td><td>ETHFI/USD</td><td>true</td></tr><tr><td>213</td><td>Crypto</td><td>METIS/USD</td><td>true</td></tr><tr><td>214</td><td>Crypto</td><td>AEVO/USD</td><td>true</td></tr><tr><td>215</td><td>Crypto</td><td>ONDO/USD</td><td>true</td></tr><tr><td>216</td><td>Crypto</td><td>MNT/USD</td><td>true</td></tr><tr><td>217</td><td>Crypto</td><td>KAS/USD</td><td>true</td></tr><tr><td>218</td><td>Crypto</td><td>RONIN/USD</td><td>true</td></tr><tr><td>219</td><td>Crypto</td><td>ENA/USD</td><td>true</td></tr><tr><td>220</td><td>Crypto</td><td>W/USD</td><td>true</td></tr><tr><td>221</td><td>Crypto</td><td>ZEUS/USD</td><td>true</td></tr><tr><td>222</td><td>Crypto</td><td>TNSR/USD</td><td>true</td></tr><tr><td>223</td><td>Crypto</td><td>TAO/USD</td><td>true</td></tr><tr><td>224</td><td>Crypto</td><td>OMNI/USD</td><td>true</td></tr><tr><td>225</td><td>Crypto</td><td>PRCL/USD</td><td>true</td></tr><tr><td>226</td><td>Crypto</td><td>MERL/USD</td><td>true</td></tr><tr><td>227</td><td>Crypto</td><td>SAFE/USD</td><td>true</td></tr><tr><td>228</td><td>Crypto</td><td>SAGA/USD</td><td>true</td></tr><tr><td>229</td><td>Crypto</td><td>LL/USD</td><td>false</td></tr><tr><td>230</td><td>Crypto</td><td>MSN/USD</td><td>false</td></tr><tr><td>231</td><td>Crypto</td><td>REZ/USD</td><td>true</td></tr><tr><td>232</td><td>Crypto</td><td>NOT/USD</td><td>true</td></tr><tr><td>233</td><td>Crypto</td><td>IO/USD</td><td>true</td></tr><tr><td>234</td><td>Crypto</td><td>BRETT/USD</td><td>true</td></tr><tr><td>235</td><td>Crypto</td><td>ATH/USD</td><td>true</td></tr><tr><td>236</td><td>Crypto</td><td>ZRO/USD</td><td>true</td></tr><tr><td>237</td><td>Crypto</td><td>ZK/USD</td><td>true</td></tr><tr><td>238</td><td>Crypto</td><td>LISTA/USD</td><td>true</td></tr><tr><td>239</td><td>Crypto</td><td>BLAST/USD</td><td>false</td></tr><tr><td>240</td><td>Crypto</td><td>RATS/USD</td><td>true</td></tr><tr><td>241</td><td>Crypto</td><td>BNX/USD</td><td>true</td></tr><tr><td>242</td><td>Crypto</td><td>PEOPLE/USD</td><td>true</td></tr><tr><td>243</td><td>Crypto</td><td>TURBO/USD</td><td>true</td></tr><tr><td>244</td><td>Crypto</td><td>SATS/USD</td><td>true</td></tr><tr><td>245</td><td>Crypto</td><td>POPCAT/USD</td><td>true</td></tr><tr><td>246</td><td>Crypto</td><td>MOG/USD</td><td>true</td></tr><tr><td>247</td><td>Crypto</td><td>OM/USD</td><td>true</td></tr><tr><td>248</td><td>Crypto</td><td>CORE/USD</td><td>true</td></tr><tr><td>249</td><td>Crypto</td><td>JASMY/USD</td><td>true</td></tr><tr><td>250</td><td>Crypto</td><td>DAR/USD</td><td>true</td></tr><tr><td>251</td><td>Crypto</td><td>MEW/USD</td><td>true</td></tr><tr><td>252</td><td>Crypto</td><td>DEGEN/USD</td><td>true</td></tr><tr><td>253</td><td>Crypto</td><td>SLERF/USD</td><td>true</td></tr><tr><td>254</td><td>Crypto</td><td>UXLINK/USD</td><td>false</td></tr><tr><td>255</td><td>Crypto</td><td>AVAIL/USD</td><td>true</td></tr><tr><td>256</td><td>Crypto</td><td>BANANA/USD</td><td>true</td></tr><tr><td>257</td><td>Crypto</td><td>RARE/USD</td><td>true</td></tr><tr><td>258</td><td>Crypto</td><td>SYS/USD</td><td>true</td></tr><tr><td>259</td><td>Crypto</td><td>NMR/USD</td><td>true</td></tr><tr><td>260</td><td>Crypto</td><td>RSR/USD</td><td>true</td></tr><tr><td>261</td><td>Crypto</td><td>SYN/USD</td><td>true</td></tr><tr><td>262</td><td>Crypto</td><td>AUCTION/USD</td><td>true</td></tr><tr><td>263</td><td>Crypto</td><td>ALICE/USD</td><td>true</td></tr><tr><td>264</td><td>Crypto</td><td>SUN/USD</td><td>true</td></tr><tr><td>265</td><td>Crypto</td><td>TRB/USD</td><td>true</td></tr><tr><td>266</td><td>Crypto</td><td>DOGS/USD</td><td>true</td></tr><tr><td>267</td><td>Crypto</td><td>SSV/USD</td><td>true</td></tr><tr><td>268</td><td>Crypto</td><td>PONKE/USD</td><td>true</td></tr><tr><td>269</td><td>Crypto</td><td>POL/USD</td><td>true</td></tr><tr><td>270</td><td>Crypto</td><td>RDNT/USD</td><td>true</td></tr><tr><td>271</td><td>Crypto</td><td>FLUX/USD</td><td>true</td></tr><tr><td>272</td><td>Crypto</td><td>NEIRO/USD</td><td>true</td></tr><tr><td>273</td><td>Crypto</td><td>SUNDOG/USD</td><td>true</td></tr><tr><td>274</td><td>Crypto</td><td>CAT/USD</td><td>true</td></tr><tr><td>275</td><td>Crypto</td><td>BABYDOGE/USD</td><td>false</td></tr><tr><td>276</td><td>Crypto</td><td>REEF/USD</td><td>true</td></tr><tr><td>277</td><td>Crypto</td><td>CKB/USD</td><td>true</td></tr><tr><td>278</td><td>Crypto</td><td>CATI/USD</td><td>true</td></tr><tr><td>279</td><td>Crypto</td><td>LOOM/USD</td><td>true</td></tr><tr><td>280</td><td>Crypto</td><td>ZETA/USD</td><td>true</td></tr><tr><td>281</td><td>Crypto</td><td>HMSTR/USD</td><td>true</td></tr><tr><td>282</td><td>Crypto</td><td>EIGEN/USD</td><td>true</td></tr><tr><td>283</td><td>Crypto</td><td>POLYX/USD</td><td>true</td></tr><tr><td>284</td><td>Crypto</td><td>MOODENG/USD</td><td>true</td></tr><tr><td>285</td><td>Crypto</td><td>MOTHER/USD</td><td>true</td></tr><tr><td>286</td><td>Crypto</td><td>AERO/USD</td><td>true</td></tr><tr><td>287</td><td>Crypto</td><td>CVC/USD</td><td>true</td></tr><tr><td>288</td><td>Crypto</td><td>NEIROCTO/USD</td><td>true</td></tr><tr><td>289</td><td>Crypto</td><td>ARK/USD</td><td>true</td></tr><tr><td>290</td><td>Crypto</td><td>NPC/USD</td><td>false</td></tr><tr><td>291</td><td>Crypto</td><td>ORBS/USD</td><td>true</td></tr><tr><td>292</td><td>Crypto</td><td>APU/USD</td><td>true</td></tr><tr><td>293</td><td>Crypto</td><td>BSV/USD</td><td>true</td></tr><tr><td>294</td><td>Crypto</td><td>HIPPO/USD</td><td>true</td></tr><tr><td>295</td><td>Crypto</td><td>GOAT/USD</td><td>true</td></tr><tr><td>296</td><td>Crypto</td><td>DOG/USD</td><td>false</td></tr><tr><td>297</td><td>Crypto</td><td>HOT/USD</td><td>true</td></tr><tr><td>298</td><td>Crypto</td><td>STORJ/USD</td><td>true</td></tr><tr><td>299</td><td>Crypto</td><td>RAY/USD</td><td>true</td></tr><tr><td>300</td><td>Crypto</td><td>BTCDEGEN/USD</td><td>true</td></tr><tr><td>301</td><td>Crypto</td><td>PNUT/USD</td><td>true</td></tr><tr><td>302</td><td>Crypto</td><td>ACT/USD</td><td>true</td></tr><tr><td>303</td><td>Crypto</td><td>GRASS/USD</td><td>true</td></tr><tr><td>304</td><td>Crypto</td><td>ZEN/USD</td><td>true</td></tr><tr><td>305</td><td>Crypto</td><td>LUMIA/USD</td><td>true</td></tr><tr><td>306</td><td>Crypto</td><td>ALPH/USD</td><td>true</td></tr><tr><td>307</td><td>Crypto</td><td>VIRTUAL/USD</td><td>true</td></tr><tr><td>308</td><td>Crypto</td><td>SPX/USD</td><td>true</td></tr><tr><td>309</td><td>Crypto</td><td>ACX/USD</td><td>true</td></tr><tr><td>310</td><td>Crypto</td><td>CHILLGUY/USD</td><td>true</td></tr><tr><td>311</td><td>Crypto</td><td>CHEX/USD</td><td>false</td></tr><tr><td>312</td><td>Crypto</td><td>BITCOIN/USD</td><td>true</td></tr><tr><td>313</td><td>Crypto</td><td>ETHDEGEN/USD</td><td>true</td></tr><tr><td>314</td><td>Crypto</td><td>SOLDEGEN/USD</td><td>true</td></tr><tr><td>315</td><td>Crypto</td><td>MOVE/USD</td><td>true</td></tr><tr><td>316</td><td>Crypto</td><td>ME/USD</td><td>true</td></tr><tr><td>317</td><td>Crypto</td><td>COW/USD</td><td>true</td></tr><tr><td>318</td><td>Crypto</td><td>AVA/USD</td><td>true</td></tr><tr><td>319</td><td>Crypto</td><td>USUAL/USD</td><td>true</td></tr><tr><td>320</td><td>Crypto</td><td>PENGU/USD</td><td>true</td></tr><tr><td>321</td><td>Crypto</td><td>FARTCOIN/USD</td><td>true</td></tr><tr><td>322</td><td>Crypto</td><td>ZEREBRO/USD</td><td>true</td></tr><tr><td>323</td><td>Crypto</td><td>AI16Z/USD</td><td>true</td></tr><tr><td>324</td><td>Crypto</td><td>AIXBT/USD</td><td>true</td></tr><tr><td>325</td><td>Crypto</td><td>BIO/USD</td><td>true</td></tr><tr><td>326</td><td>Apechain only</td><td>XRPDEGEN/USD</td><td>true</td></tr><tr><td>327</td><td>Apechain only</td><td>BNBDEGEN/USD</td><td>true</td></tr><tr><td>328</td><td>Crypto</td><td>TRUMP/USD</td><td>true</td></tr><tr><td>329</td><td>Crypto</td><td>MELANIA/USD</td><td>true</td></tr><tr><td>330</td><td>Crypto</td><td>MODE/USD</td><td>false</td></tr><tr><td>331</td><td>Crypto</td><td>HYPE/USD</td><td>true</td></tr><tr><td>332</td><td>Crypto</td><td>S/USD</td><td>true</td></tr><tr><td>333</td><td>Crypto</td><td>ARC/USD</td><td>true</td></tr><tr><td>334</td><td>Crypto</td><td>ARKM/USD</td><td>true</td></tr><tr><td>335</td><td>Crypto</td><td>GRIFFAIN/USD</td><td>true</td></tr><tr><td>336</td><td>Crypto</td><td>SWARMS/USD</td><td>true</td></tr><tr><td>337</td><td>Crypto</td><td>ANIME/USD</td><td>true</td></tr><tr><td>338</td><td>Crypto</td><td>PLUME/USD</td><td>true</td></tr><tr><td>339</td><td>Crypto</td><td>VVV/USD</td><td>true</td></tr><tr><td>340</td><td>Crypto</td><td>VINE/USD</td><td>true</td></tr><tr><td>341</td><td>Crypto</td><td>TOSHI/USD</td><td>true</td></tr><tr><td>342</td><td>Crypto</td><td>BERA/USD</td><td>true</td></tr><tr><td>343</td><td>Crypto</td><td>LAYER/USD</td><td>true</td></tr><tr><td>344</td><td>Crypto</td><td>CHEEMS/USD</td><td>true</td></tr><tr><td>345</td><td>Crypto</td><td>SOLV/USD</td><td>true</td></tr><tr><td>346</td><td>Crypto</td><td>TST/USD</td><td>true</td></tr></tbody></table>


# How to use Practice Mode

The Practice mode can be used in order to test gTrade as though you are live trading, but without using collateral with value. It is done on the **Arbitrum Sepolia Testnet.**

You will need:

1. A Web3 wallet like Rabby or Metamask connected to the Arbitrum Sepolia Testnet
2. Testnet ETH to pay for transactions
3. Testnet DAI to use as collateral

Let's set it up:\
\
1\. The fastest way is to click the Network dropdown on gains.trade, click the network dropdown and click Sepolia - Practice. This should prompt your wallet to add the Arbitrum Sepolia network.

<figure><img src="/files/9OfNVBunK1gEMefkkgzw" alt=""><figcaption><p>Select Sepolia from the dropdown menu.</p></figcaption></figure>

Alternatively you can go to <https://sepolia.arbiscan.io/>, scroll to the bottom and click "Add Arbitrum One Sepolia Network" on the right.

<figure><img src="/files/5yi6WsCrT8GFtIBTb22E" alt=""><figcaption><p>Scroll to the bottom of the page to see the button.</p></figcaption></figure>

2\. Next, we need some Arbitrum Sepolia Testnet ETH for gas. There are several options for this, some of which are listed below. A website that "drips" a token for testnet purposes is called a "faucet".

*(Please note that Sepolia as a testnet exists on several chains, so whichever faucet you use, be sure to select Arbitrum Sepolia)*

<https://faucets.chain.link/arbitrum-sepolia> (0.1 ETH, Requires Github login)

<https://faucet.quicknode.com/arbitrum/sepolia> (0.05-0.1 ETH, requires holding 0.001 ETH on Ethereum Mainnet)

<https://www.alchemy.com/faucets/arbitrum-sepolia> (0.1-0.5 ETH per day, requires an Alchemy account (free) and a balance of 0.001 ETH on Arbitrum Mainnet)

*There are many other faucets available. Some may be unavailable at times, if you can't find a faucet or would like help to set up Practice Mode in general, feel free to ask in our Discord or Telegram!*<br>

3\. Ensure you have selected the Sepolia - Practice option from the network dropdown on the trading page, and ensure that your wallet is connected in the top right hand corner.

Once you are connected you can click 'Approve' in the trading panel, and then click 'Get 10,000 DAI' to get your practice DAI.

<figure><img src="/files/hEPBBT9vp8uLda6HSmwl" alt=""><figcaption><p>Click Approve, send the transaction, then click Get 10,000 DAI and send the transaction.</p></figcaption></figure>

You can then use the platform as you would on the mainnet!

If your testnet DAI balance drops below 1,000 DAI, the button will show again so you can claim 10,000 DAI more.

Follow the guide [Opening and Closing a Trade](/gtrade-leveraged-trading/opening-closing-trades).


# One-Click Trading (1CT)

Forget about Metamask confirmations

## Overview

One-click trading (1CT) removes the need to interact with a wallet when submitting transactions, reducing time to trade.&#x20;

It does this through the use of two new mechanisms:

* 1CT wallet
* Trade delegation

## 1CT Wallet

gTrade uses a derived externally owned account (EOA) wallet for submitting trading transactions.&#x20;

It relies on the following sequence:

1. Trader provides a 4 digit PIN
   * *This pin should be remembered for future recovery*
2. Trader signs a prefixed message of the PIN using their wallet
   * *The wallet used to sign the message should be remembered for future recovery*
3. gTrade website generates an Secp256k1 key pair using the signed message as a seed
4. gTrade website encrypts and stores the key material on the local device

> Key material is deterministic meaning it can be replicated. Pin + personalSign gives strong security guarantees while allowing a trader to recover material if lost. A trader can also use this to prevent storing on device between trading sessions (clear and regenerate for each session).

Once a trader creates a 1CT wallet, they must grant it permissions to trade on their behalf by approving it as a delegate.

## Trade Delegation

gTrade smart contracts support a delegation feature, allowing EOAs to submit transactions on behalf of other EOAs.

To delegate trading to another EOA, a trader must approve the address as a delegate through the trading contract.&#x20;

A delegation wallet only needs gas funds for submitting transactions, as collateral and PnL are tied to the trader address.

<details>

<summary>Supported delegate actions</summary>

* Open a trade
* Open an order
* Cancel an order
* Update stop loss
* Update take profit
* Close a trade

</details>

The 1CT wallet is a delegation wallet.

## Onboard

gTrade offers an onboarding experience for all of the above:

1. Create PIN
2. Sign message
3. Approve 1CT wallet
4. Fund 1CT wallet
5. Enable feature

![](/files/2XouBoiyt5KOlCD4sDbu)

![](/files/vGR8lHtlVMwvjgdINBrA)

## Manage

Once a trader has onboarded, they may manage the feature under the accounts dropdown:

* Enable/disable the feature
* Fund 1CT wallet
* Withdraw all funds from 1CT wallet
* Export private key
* Reset/wipe all 1CT data

![](/files/AUfJTilQejlnxnN73Ngm)

![](/files/EDCEwuvPORepSjeaIh6W)

## Use

Once onboarded, a trader may enable the feature and use their normal trading workflows. At this point there is nothing different other than not having to confirm transactions in a wallet.

![](/files/jbBg5xzwQLnkLVqT2rev)

## Transactions

Because 1CT wallet is managed by the site, transaction management is taken in-house. This provides a place to track transactions and interact if they're stuck by speeding up or canceling.&#x20;

![](/files/Bfe6gmurnMWxgL3azDaT)

## 1CT on ApeChain

Because $APE is the native token of ApeChain, and doesn't follow the `approve`/ `transfer` standard, it can't be used as part of the delegateAction call pattern, the on-chain representation of 1CT.&#x20;

Fortunately, gTrade offers $gWAPE (gTrade WAPE), a WETH9 token — <https://apescan.io/address/0x62dC4f51e74Ec084F93001397975fb64BECf52E2>.&#x20;

Traders can place trades using $gWAPE in order to use 1CT.&#x20;

1. Wrap / unwrap through gTrade

<div align="center" data-full-width="true"><figure><img src="/files/VmpAPrXC6c7oxYOy45xj" alt=""><figcaption></figcaption></figure></div>

1. Approve transfer
2. Trade

NOTE: Trade collateral is returned to traders as $APE, even if opened against $gWAPE. You will have to continue to wrap after closing trades.&#x20;

## FAQ

**Is the 1CT wallet key material stored somewhere?** \
Only on your device. You can wipe it using "Reset" whenever you choose.

**I wiped my device storage, is my 1CT wallet gone?**\
Yes but you can restore it by using the same PIN and wallet when re-generating.

**Are trades opened against my 1CT wallet?**\
No, they are opened against your connected wallet.

**Do I have to have 1CT enabled to interact with trades I opened with it?** \
No, you may toggle the feature on and off whenever you'd like.

**Can I use the same 1CT wallet on multiple devices?**\
Yes, as long as you use the same PIN and wallet while generating.

**Can I use the same 1CT wallet for multiple accounts?**\
Yes, you may delegate to your 1CT wallet with any connected wallet.

**Can I have multiple 1CT wallets?**\
For each account you use to trade, you may have one delegate. The recommended setup is to use the same 1CT wallet for all trading accounts.

**What if my transaction is stuck?**\
In the accounts dropdown, you'll find a transactions list. Here you may speed up and/or cancel a stuck transaction.

**Do I have to have key material stored on device?**\
No, you can re-create your 1CT wallet and reset it at the end of each trading session. Just use the same PIN and wallet to sign.


# gTrade Solana

Trade your favorite pairs directly from your Solana wallets!

Visit gTrade Solana at ➡️ <https://sol.gains.trade/>

For more details on the Solana UX and how to open your first trades, visit this [Medium article](https://medium.com/gains-network/gtrade-solana-your-gateway-to-effortless-trading-22d1fe30bd80) or watch this [video tutorial](https://www.youtube.com/watch?v=7tpOmlTEWbM).

<figure><img src="/files/rn0dOxNU5Pn0laZn8ypu" alt=""><figcaption><p>gTrade Solana</p></figcaption></figure>


# Video tutorials

A list of YouTube videos to learn more about gTrade.

### **What is $GNS?**&#x20;

$GNS is the token that powers the gTrade ecosystem. It combines utility, deflationary tokenomics with real yield, and governance rights — giving holders the full package:&#x20;

{% embed url="<https://www.youtube.com/watch?v=40B9BVNy6tI>" %}

### **Placing Your First Trade**&#x20;

New to gTrade? This in-depth tutorial covers everything you need to get started — from setting up your wallet and funding it with crypto to enabling 1-click trading and placing your first trade:

{% embed url="<https://www.youtube.com/watch?v=3V4W50YX8bM>" %}

### **Opening a Trade**

Opening a trade on gTrade is easy. Pick your collateral of choice, approve, and start trading:

{% embed url="<https://youtu.be/FGbSATL868U>" %}

### **1-Click Trading Tutorial**

One-click trading (1CT) eliminates the need for wallet confirmations on every trade, making execution faster and smoother. Learn how to enable it:

{% embed url="<https://www.youtube.com/watch?v=QZ2GJ-BRJtk>" %}

### **How fast is 1-click trading?**

How fast is 1-click trading? See it in action — fully on-chain, non-custodial, and decentralized:

{% embed url="<https://www.youtube.com/watch?v=3FaIe7-V7U8>" %}

### **Trading Competitions on gTrade**

gTrade occasionally partners with projects that are listed on the platform by hosting a trading competition — specifically for that pair. Watch how it works:

{% embed url="<https://www.youtube.com/watch?v=_X0I1ZHeynY>" %}

### **gTrade Rewards: Trade & Earn**

gTrade frequently runs trading incentive campaigns with custom reward structures. Discover how these programs work:

{% embed url="<https://www.youtube.com/watch?v=--lQeoj1OZg>" %}

### **gTrade on ApeChain: How to Bridge & Start Trading**

gTrade is live on ApeChain! Learn how to bridge your $APE to ApeChain and start leverage trading using Rainbow Wallet:

{% embed url="<https://www.youtube.com/watch?t=44s&v=mHYeCiG1jVI>" %}

{% embed url="<https://www.youtube.com/watch?ab_channel=KyleCollins&feature=youtu.be&v=d1UCFp-9oSo>" %}


# Prime Trader

<figure><img src="/files/eGl5cvVrFB27XbCz205b" alt=""><figcaption></figcaption></figure>

Prime Trader is a loyalty program that provides traders with the best of gTrade through exclusive benefits. The program was [rolled out in January 2025](https://x.com/GainsNetwork_io/status/1877553929489154532) with the first perk: exemption from increased spreads on early position closes for altcoins.

More benefits — such as gas credits — are added to the program over time.

**Eligibility:** All organic traders are welcome to apply. The protocol reserves the right to revoke your benefits if exploitative behavior is identified.

Apply here ➡️ <https://forms.gle/R4qKs5zdpVTtQg2q9>


# gTrade Credits

<figure><img src="/files/9WJUq2k9gnBnAiiiPOsO" alt=""><figcaption></figcaption></figure>

gTrade Credits is a loyalty program that offers tiered fee discounts, letting you save more the more you trade.

Tiers are broken down as follows:

| Tier | Credits (30D) | Discount |
| ---- | ------------- | -------- |
| 1    | 6M            | 2.5%     |
| 2    | 20M           | 5.0%     |
| 3    | 50M           | 7.5%     |
| 4    | 100M          | 10.0%    |
| 5    | 250M          | 13.0%    |
| 6    | 400M          | 15.0%    |
| 7    | 1,000M        | 20.0%    |
| 8    | 2,000M        | 25.0%    |

Different asset classes contribute to your gTrade Credits balance as follows:

<table data-header-hidden><thead><tr><th>How to Earn</th><th width="100"></th></tr></thead><tbody><tr><td><strong>How to Earn</strong><br><br>Breakdown of how many credits you earn per $1 of volume traded. Credits are earned on open and close.</td><td></td></tr><tr><td><strong>Group</strong></td><td><strong>Credits</strong></td></tr><tr><td>Crypto</td><td>6</td></tr><tr><td>FX Major</td><td>1.2</td></tr><tr><td>FX Minor</td><td>1.6</td></tr><tr><td>FX Exotic</td><td>2</td></tr><tr><td>altcoins</td><td>2</td></tr><tr><td>Commodities 1</td><td>5</td></tr><tr><td>Commodities 2</td><td>8</td></tr></tbody></table>

Check out your accrued credits and current tier here ➡️ <https://gains.trade/portfolio/credits>

*For more details on gTrade Credits, visit the* [*Medium article*](https://medium.com/gains-network/introducing-gtrade-credits-trade-more-save-more-cb996ed536dc)*.*

### **Trading with size?**

Large traders can apply for reduced fees through gTrade Credits — by up to 25%.

**Eligibility:** If you have actively traded on other PerpDEX or CEX venues in the past 6 months, you're invited to apply!

Apply to get fast-tracked here ➡️ <https://forms.gle/2ACghN8gz4mPqBWW7>


# gTrade Guardians

Become a gTrade Guardian and champion the future of DeFi

## Mission

The gTrade Guardians program is designed to create a strong sense of family and belonging within a global community of passionate individuals. Representation of gTrade in the digital world is being redefined, with Guardians empowered to track their progress and grow through tangible achievements. Support is provided to help Guardians craft creative content that inspires, educates, and amplifies the vision of the gTrade platform.

## Get Involved

1. **Sign Up** – Please fill out this Google form:  <https://docs.google.com/forms/d/e/1FAIpQLSftE8n3u7KOhNcC03FerjJryb-ggw5-w3uA7r-P9_MlOtqgHw/viewform>
2. **Vetting Process** – A gTrade representative will review your application.
3. **One-on-One Interview** – If you’re selected for the program, you will receive an invite for an interview as the final step in your vetting process.

## Onboarding    &#x20;

What to expect when first starting:   &#x20;

* **Access** to dedicated gTrade Ambassador **Telegram group** – Share content, get feedback and connect with others.
* **Program Details** – Guidelines, incentives, tier system
* **Monthly Group Calls** – Learn about gTrade, content creation and program updates.

## KPIs and Rewards

*Create Content, Unlock Rewards!*

Meet the KPI requirements and receive the corresponding benefits:

**⭐️ 10,000 monthly views**

* Referral link (optional)
* gTrade Guardian Discord/Telegram role
* Dedicated GNS-chan NFT showcasing Guardian status

**⭐️ 25,000 monthly views**

* Verified blue checkmark
* Content promotion via official channels and gTrade Guardian account

**⭐️ 50,000 monthly views**

* Exclusive gTrade merch

**⭐️ 100,000 monthly views**

* Invitation to gTrade events
* Access to, and ability to give feedback on, coming updates
* Higher revenue share

**⭐️ 500,000 monthly views**

* Ability to earn $GNS rewards
* Ability to run an official gTrade related account (e.g. gTrade Lifestyle and gTrade Gym)
* Recognition as part of the gTrade family

***Also, posts are always eligible to be tipped!***\
\
Here are some of the criteria gTrade will look at:

* Most creative post
* ATH in views
* Best likes-to-view ratio
* Most KPIs reached
* High engagement
* Highest amount of views
* Highest amount of likes

A monthly review of the gTrade Guardian’s performance will be conducted, e.g. tracking number of views.

## Minimum Requirement

The gTrade Guardian Ambassador program requires you to post  gTrade and Gains Network-related content 4 times per month.

## Content Guidelines     &#x20;

As a gTrade Guardian, your content helps shape the community and spreads the word about Gains Network. Encourage creativity and humor while ensuring that all content aligns with community values. Please keep the following guidelines in mind:&#x20;

**Be inclusive and respectful.**

* No racism or discrimination: We have zero tolerance for racism, sexism, homophobia, or any other form of discrimination. Your content should be welcoming and respectful of everyone, regardless of their background.
* No harassment or bullying: Harassment, bullying, or any form of intimidation is strictly prohibited. We want a positive and supportive community, so make sure your content reflects that.

**Encourage creativity and humor.**

* Memes and jokes are welcome: We love creativity! Feel free to share memes, jokes, and lighthearted content. Just ensure it’s in good taste and doesn’t cross the line into offensive or harmful territory.
* Stay true to the brand: While having fun, remember to keep your content aligned with the values and mission of Gains Network and gTrade. Focus on the positive aspects of the platform and the DeFi space.

**Promote positive interaction.**

* Constructive Criticism: When offering feedback or criticism, keep it constructive and aimed at fostering improvement. A positive tone helps maintain a strong and supportive community.
* Engage Responsibly: Interact with others online in a way that builds the community. Avoid getting involved in conflicts or negative exchanges.

**Respect legal and ethical boundaries.**

* No Misinformation: Share accurate and reliable information. Avoid spreading rumors or unverified claims.
* Copyright and Attribution: Ensure your content is original or properly credited. Respect others’ intellectual property.

**Use official hashtags.**

* Hashtag & Tag Use: When posting about gTrade, use the official hashtags (#gTrade, #GainsNetwork & @GainsNetwork\_Io) to connect with the community and amplify your reach.

**Report issues.**

* Flag Inappropriate Content: If you see content that doesn’t align with these guidelines, report it to the Gains Network team.


# GNS Staking

Stake $GNS to get a share of the gTrade revenue!

**Note:** Following a [Snapshot vote](https://snapshot.org/#/s:gains-network.eth/proposal/0xdbace14c86becd08e0ee5dad6d558bcea08728c623809c113c530b7c5fd7dd4f), all staking rewards are being used to *buy back and burn* (BB\&B) $GNS from the open market. This will continue [indefinitely](https://snapshot.org/#/s:gains-network.eth/proposal/0xff7fe3c76890a5ed4bc272f82d9cc4fbb761576a4781e74cf5abec0f21aa738f) until a new vote is passed.

Keep track of the $GNS burn metrics here ➡️ <https://gains.trade/staking>

* Or this [Dune dashboard](https://dune.com/midgetwhale/gns-burn)

For more details on the $GNS tokenomics, refer to [GNS Token](/what-is-gains-network/gfarm2-token)

## Staking GNS

In July 2024, gTrade [introduced the Buyback and Distribute model (BB\&D)](https://medium.com/gains-network/evolving-gains-network-tokenomics-introducing-buyback-and-distribute-c15ce1fa8fdb) to reward $GNS stakers with 55% of the protocol’s revenue. This allocation is now used to buyback & burn $GNS from the open market.&#x20;

The tokenomics have been designed to adapt over time, ensuring flexibility in response to both community demand and market conditions. $GNS holders may stake their tokens to earn a share of the gTrade’s revenue in case direct revenue sharing (SSS or BB\&D) is turned back on. In the meantime, all $GNS holders are seeing revenue sharing through continuous buybacks & burns.

## Buyback & Burn

Around 60% of the open and close fees generated by the platform ($USDC, $DAI, $WETH) are used to buy back $GNS OTC using the 1 hour TWAP + a 1% premium to ensure a reliable arbitrage opportunity. Buying back $GNS with the non-GNS collaterals both creates a sustained buying pressure and a more stable price floor, as well as helps retain value within the ecosystem.

The revenue can be distributed to **$GNS stakers**, the **governance fund**, or the **burn address**. This allocation of revenue is flexible and is currently set to: 90% $GNS burn (`60% * 0.9 = 54%`), 10% governance fund (`60% * 0.1 = 6%`).

You can read more about the Buyback & Distribute (or Burn) tokenomics in this [Medium article](https://medium.com/gains-network/evolving-gains-network-tokenomics-introducing-buyback-and-distribute-c15ce1fa8fdb).

## Audit

Our staking contract has been audited here: <https://github.com/pashov/audits/blob/master/solo/gTrade-security-review.md>

## $GNS Staking FAQ

**Are my staked $GNS locked for a certain period of time?**

There is currently no timelock for staking $GNS, and you are able to withdraw at any time.

**What's the difference between the buttons "*****Harvest*****" and "*****Compound*****"?**

*Harvest* transfers your rewards to your wallet. *Compound* harvests your rewards and restakes them, in a single transaction.

**I staked before September 30, 2023 and I can't find my staked $GNS. Where are they?**

Your $GNS is in the deprecated vault. The staking vault was upgraded in late September 2023, and you can unstake your $GNS from the old vault here: <https://gains.trade/staking-legacy>


# gToken Vaults

Collateral vaults supporting trading liquidity

**Current gToken Vaults**: gUSDC, gDAI, gETH, gAPE, gGNS, gBTCUSD

gToken vaults follow ERC-4626, a standard API for tokenized yield-bearing vaults that represent shares of a single underlying ERC-20 asset. For each vault, gToken shares represent the underlying token asset (I.e. gDAI => DAI).

Vaults serve as a counterparty to all trades made on the platform:

* When traders win (positive PnL), their winnings are received from the vault.&#x20;
* When traders lose (negative PnL), their losses are sent to the vault.

In exchange, the vault receives a portion of trading fees. These fees are proportionally split among gToken shares, incentivizing stakers to stay in the vault.

The vault that earns fees, pays profits, and bears losses, is determined by the collateral of each trade.&#x20;

Collateralization of the vault depends on trader PnL. As long as fees earned is greater than PnL payouts, stakers earn a positive return. This has proven to be the case for 2+ years and the protocol has various risk management measures in place to ensure it continues.

Net losses are used to create a buffer, further protecting stakers' funds and the protocol from future PnL abnormalities.

To better approximate real collateralization ratio, and to minimize risks for the protocol (including stakers), the vault follows an epoch system for capturing snapshots of open PnL. Open PnL represents the aggregate PnL of all open trades at the time of the snapshot.

## gToken

gTokens are ERC-20s representing ownership of the underlying token asset. It follows an exchange rate model (similar to Compound's cTokens) where the price of gToken to asset changes in real-time from two variables: accumulated fees and trader PnL (both open and closed).

*`gToken = 1 + accRewardsPerToken — Math.max(0, accPnlPerTokenUsed)`*

`accRewardsPerToken`: accumulator value representing how many fees a single gToken has accrued. This value always increases over time.

`accPnlPerTokenUsed`: a snapshotted accumulator value of trader PnL from all closed trades and a snapshot of open trades from the end of the previous epoch. This value changes every epoch and can move in either direction.

To summarize, the vault consists of two parts:

* The asset staked by stakers, which corresponds 100% collateralization
* The overcollaterization layer, which makes up anything beyond 100%\
  \&#xNAN;*-> note that the overcollateralization layer doesn't make the gToken price increase, see gToken price formula above.*

*Thus if the vault is at 110% it means that the OC is at 10%.*

The overcollateralization layer (OC) acts as a buffer between traders and lenders, and profits and losses are paid out, or paid to, the OC as long as it exists. By design, the vault can be in two states; overcollaterized (>=100%) and undercollaterized (<100%).

* If the vault is **overcollateralized**, a percentage of trader losses is diverted to a pool where users can sell GNS for the asset, OTC, using the 1-hour TWAP. This enables users to sell GNS without paying any slippage that would occur on an exchange, or affecting the GNS price. This GNS is then burned, to counteract any minting that happens while under-collateralized.
* If the vault is **undercollateralized**, GNS is minted and sold for the asset, OTC. The asset is then used to replenish the vault. A maximum of 0.05% of the total supply of GNS can be minted every 24h (18.25% per year). Again, this creates a secondary market where users can buy GNS without having to pay any slippage. (*Please note that in the case of BtcUSD, $GNS will not be minted in order to replenish an undercollateralized vault, it instead relies on its partner — Bifrost — to restore the overcollateralization buffer.*)
* Both the mints and burns are entirely decentralized and only happen when someone interacts with the vault. The interface for it is located at <https://gains.trade/otc>

<figure><img src="/files/5OlHorCRNboKrsGH1W48" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/bpv1tIE5IcFo7cYFnLMo" alt=""><figcaption></figcaption></figure>

## gNFT

gNFT is an ERC-721 representing ownership of locked gToken shares. Locked gToken is purchased at a discount, based on the amount of time a lender is willing to lock up their funds, and can be unlocked following the lock duration.&#x20;

Locked gToken accumulates fees like all other shares.

## Epoch system

Epoch system provides open PnL data to the vault in a decentralized manner, so the vault better understands its collateralization ratio. Calculating open PnL is too computationally expensive to do in real-time, on-chain.&#x20;

There are two states the epoch system can be in:

* **Withdraw window** - the period before open PnL values are being received and stakers may make withdraw-related actions (both requests and withdraws).
* **Open PnL window** - the period before the epoch closes where the protocol requests open PnL snapshots from oracles. It makes multiple requests to a network of oracles, taking the median value, finally averaging across the request periods. This PnL value is then used in the succeeding epoch.

## Withdraw locks

For the security of the vault, and to prevent stakers from front-running PnL changes, assets can't be withdrawn immediately. Instead they must go through a withdraw request system.

Depending on the collateralization ratio of the vault, a staker may withdraw either 1, 2, or 3 epochs after making a request. The higher collateralization ratio, the shorter the lock period. It's important to note that the gTokens continue to accrue value even after a withdrawal request has been made.

If a staker misses their withdraw window, they must make a new request.

For a more detailed overview of the vault, please see our Medium post:

{% embed url="<https://medium.com/gains-network/introducing-gtoken-vaults-ea98f10a49d5>" %}

## Audit

{% file src="/files/xsZrNA7skYMdwMiPTNi7" %}


# Staker Functions

https\://gains.trade/vault

{% hint style="info" %}
These functions apply to all gToken vaults. gDAI is used for demonstration.
{% endhint %}

## Deposit

Deposit DAI in exchange for gDAI. See [#gDAI](https://gains-network.gitbook.io/docs-home/liquidity-farming-pools/gdai-vault#gdai) in overview.

You can deposit at anytime.

![](/files/jfjr4Qlq16YKp3Y2mE9j)

## Deposit with discount and lock

Deposit DAI into the vault in exchange for a gNFT, which represents rights to locked gDAI.&#x20;

Discount percentage is based on the current collateralization ratio of the vault and the duration the staker is willing to lock gDAI for.

You can deposit at anytime.

See [#gNFT](https://gains-network.gitbook.io/docs-home/liquidity-farming-pools/gdai-vault#gnft) in overview.

Current maximum discount: 5%

Current lock window: \[7d, 365d]

![](/files/iGAYl3taDAq1r7PZyXTX)

## Unlock

gNFT holders are able to claim gDAI anytime after the unlock date by unlocking through the UI. This function burns the NFT and transfers gDAI to owner's wallet.

![](/files/2MVVOGEcVev1I40ADDf2)

## Withdraw Request

Make a withdraw request for any amount of unlocked gDAI.

This can only be done during the withdraw window of an epoch.&#x20;

See [#Withdraw-Locks](https://gains-network.gitbook.io/docs-home/liquidity-farming-pools/gdai-vault#withdraw-locks) in overview.

![](/files/AX9fRlFZCeNv1LrXaegY)

## Withdraw

When a withdraw request's epoch is the active epoch, the requested amount may be redeemed. If the epoch window is missed, the request becomes invalid and a new request must be made.

This can only be done during the withdraw window of an epoch.

See [#Withdraw-Locks](https://gains-network.gitbook.io/docs-home/liquidity-farming-pools/gdai-vault#withdraw-locks) in overview.

![](/files/WPCV0jW7n3nzSVJpsbav)


# Staker FAQ

Answers to common staking questions

## Why can't I immediately withdraw my funds?

For the security of the vault, and to prevent stakers from front-running PnL changes.

## What determines when I can withdraw my funds?

The collateralization ratio of the vault, determined using the snapshotted total PnL from the beginning of the current epoch.&#x20;

Depending on the ratio, you can withdraw your funds in 1 (ratio > 120%), 2 (> 110%), or 3 epochs.

## Can I withdraw my funds anytime after my withdraw epoch?

**NO!** This is important. You may only withdraw your funds during your designated withdraw epoch. If you miss the window, you need to make a new request. Please note that you manually have to withdraw the tokens during the designated window that is displayed after requesting a withdrawal. (2 transactions in total)

## Do gTokens still accrue value after I have requested a withdrawal?

Yes.

## What's the purpose of the epoch system?

To provide the vault with snapshotted open PnL data, which factors into the collateralization ratio.&#x20;

As an example, if the vault has 100k DAI deposited, and 20k DAI in negative PnL, the vault appears over-collateralized (120%). It's covering staker deposits + a 20k DAI buffer.

But suppose there is 40K DAI in positive open PnL. This is not captured by the vault, as the PnL is not final. But it should not behave as if it is over collateralized, as it has a potential outstanding liability of 20k (40k positive open PnL - 20k negative PnL), or a collat ratio of 80%.&#x20;

## What happens if open PnL closes during an epoch?

Because a snapshot of open PnL is used for each epoch, there is a risk that it will close during the 3 day epoch, thus counting towards total PnL twice as much as it should.

To protect agains this, PnL updates during an epoch do not impact price: A snapshot of total PnL is used.&#x20;

The vault still tracks all closed PnL during an epoch, but it also does not impact the price or collateralization ratio until the next epoch, as a way of synchronizing open and closed PnL data.

## Can I unlock my gTokens anytime after my unlock date?

Yes, you may unlock gTokens for any gNFT you own anytime after the unlock date.

## What happens if I transfer my gNFT to another wallet?

That wallet becomes the new owner and has rights to the gTokens on unlock.

## Why can't I transfer my gTokens?

You have a pending withdraw request open. Withdraw requests lock gTokens to your wallet for the duration. Of course any other gTokens you have can be transferred, only the amount staged for withdraw can't.

This is to prevent gaming the withdraw request system.

## How is "Estimated Earnings" calculated on Vault webpage?

Estimated Earnings is an approximation of how much you've earned.

> *Using gDAI as an example: estimated earnings = gDAI balance (locked and unlocked) market value  + total DAI withdrawn - total DAI deposited*

**Why is it an "estimate"?** Because gDAI is an ERC20, it is transferrable. You can transfer to a separate wallet, swap on a secondary market, stake as collateral. Any transfer out of or into your wallet is considered a market rate swap (same as a withdrawals and deposits). In actuality it is unlikely gDAI is swapped at market rate.

For example, if you purchase 50 gDAI at a rate of 1 gDAI / DAI then transfer 20 gDAI to another wallet when the exchange rate was 1.5 gDAI / DAI you'll have an estimated earnings:

**Estimated earnings** = (30 gDAI balance \* 1.5 gDAI / DAI)  + (20 gDAI transfer \* 1.5 gDAI / DAI) - 50 DAI  = 45 + 30 - 50 = **25 DAI**

The same is true for locked gDAI (gNFT). They are transferrable and the same assumptions are made when doing so.


# Upgrades, updates, and timelocks

Contract security measures

## Contract upgrades

gDAI Vault is an upgradable contract. This is to minimize the impact on traders and stakers if the vault were to go through iterations.

To protect stakers from upgrades that would be deemed harmful to them (I.e. a compromised wallet), upgrades go through a 14 day timelock contract. Timelock duration will always be longer than the maximum amount of time to withdraw assets.

## Variable updates

gDAI Vault and the epoch system contain mutable state variables. Depending on the impact of updating a variable, it may only be updated by a 3 day or 14 day timelock contract. The following roles are in place:

* **GTokenAdmin** - no timelock, for urgent actions that **do not** impact user funds.&#x20;
* **GTokenManager** - 3 day timelock, for non urgent actions that **do not** impact user funds.
* **GTokenOwner** - 14 day timelock, for non urgent actions that **could** impact user funds


# Active Pools & Incentives

This page contains up-to-date information on $GNS and gToken pools & incentives

<details>

<summary><img src="/files/GlOdfLnY9lDwjEtkIuMm" alt="" data-size="line"> Base</summary>

**Timeswap**\
[gUSDC/USDC, lend](https://app.timeswap.io/lend/a4c3c89a-fee2-44c8-9600-1074da400652)\
[gUSDC/USDC, borrow](https://app.timeswap.io/borrow/a4c3c89a-fee2-44c8-9600-1074da400652)\
\
**Maverick**\
[USDC-gUSDC boosted position](https://app.mav.xyz/boosted-position/0x27fFd5a3828275c5938b9bE7a8db44b7DB897A34/0xB2E6E155f3c6A12FB0708B75224c50d6aE2b03FC?chain=8453\&f=true)

</details>

<details>

<summary><img src="/files/JKz97fe9YkdM2asAqhrq" alt="" data-size="line"> Arbitrum</summary>

**Pendle**\
[gDAI LP pool](https://app.pendle.finance/trade/pools/0xa9104b8b6698979568852c30231871e28a482b3c/zap/in?chain=arbitrum)\
[gUSDC LP pool](https://app.pendle.finance/trade/pools/0xa877a0e177b54a37066c1786f91a1dab68f094af/zap/in?chain=arbitrum)\
\
**Penpie**\
[Pendle gDAI LP boosted staking](https://www.pendle.magpiexyz.io/stake/0xA9104b8B6698979568852C30231871e28A482b3C)\
\
**Camelot**\
[GNS-ETH v3](https://app.camelot.exchange/pools/0x9b6FF025AeE245D314c09F57B72f0dE6E231c3a6)\
[GNS-USDC v3](https://app.camelot.exchange/pools/0x1f3572BaeE36360D23E976c244E08160523Ce7eB)\
[gUSDC-USDC v3](https://app.camelot.exchange/pools/0x1470b62eB67225f6EcDF8249293C8052f1cd2717)\
\
**Timeswap**\
[USDC/pt-gUSDC, Lend](https://app.timeswap.io/lend/3ddff11d-768c-4b3a-8617-264be2dca259)\
[USDC/pt-gUSDC, Borrow](https://app.timeswap.io/borrow/3ddff11d-768c-4b3a-8617-264be2dca259)\
\
**Maverick**\
[USDC-gUSDC](https://app.mav.xyz/boosted-position/0x4830c06cb23bB787A4f1925d26aEc9E4b828Bb37/0x57C57352f9D5e1679bB9D7c969679204478CE3f5?chain=42161\&f=true)\
\
**Silo**\
[GNS, ETH, USDC.e market](https://app.silo.finance/silo/0xfc6778a6955e1ceCAc448051de967f9b5Ff4D647)

</details>

<details>

<summary><img src="/files/VmhXApkWSotuDj8Q7n6N" alt="" data-size="line"> Polygon</summary>

**Quickswap**\
[GNS/wPOL v3](https://quickswap.exchange/#/swap?inputCurrency=0xe5417af564e4bfda1c483642db72007871397896\&outputCurrency=0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270\&swapIndex=0)

</details>


# FAQ

Frequently asked questions on the protocol.

On this page:

1. [On which chains are gTrade available and how do I get funds there to trade with?](#1.-on-which-chains-are-gtrade-available-and-how-do-i-get-funds-there-to-trade-with)
2. [What's DAI?](#2.-whats-dai)
3. [What's GFARM2 and GNS?](#3.-whats-gfarm2-and-gns)
4. [I can't open a trade with 10 DAI - is there a minimum position size?](#4.-i-cant-open-a-trade-with-10-dai-is-there-a-minimum-position-size)
5. [How do I set up practice mode?](#5.-how-do-i-set-up-practice-mode)
6. [What is slippage?](#6.-what-is-slippage)
7. [Why is the coin/asset I want to trade not listed?](#7.-why-is-the-coin-asset-i-want-to-trade-not-listed)
8. [Forex/Commodities says "Closed". Why?](#8.-forex-stocks-indices-commodities-says-closed-.-why)
9. [Where does the collateral go when I close for a profit/loss?](#9.-where-does-collateral-go-when-i-close-for-a-profit-loss)
10. [I closed my trade and don't see it in the trades history, why?](#10.-i-closed-my-trade-and-dont-see-it-in-the-trade-history-why)
11. [Can I go into debt?](#11.-can-i-go-into-debt)
12. [Does profit taking close my position?](#12.-does-profit-taking-close-my-position)
13. [Can I use other stablecoins as collateral?](#13.-can-i-use-other-stablecoins-as-collateral)
14. [I have a lot of collateral. How do I know gTrade is safe?](#14.-i-have-a-lot-of-collateral.-how-do-i-know-gtrade-is-safe)
15. [What is the "0/2 Confirmations" that appears?](#15.-what-is-the-0-2-confirmations-notification-that-appears)
16. [Where else can I find help if I have a problem or question?](#16.-where-else-can-i-find-help-if-i-have-a-problem-or-question)
17. [Why is price impact necessary?](#17.-why-is-price-impact-necessary)

#### **1. On which chains are gTrade available and how do I get funds there to trade with?**

gTrade is available on Polygon and Arbitrum One.

Polygon is a side chain to Ethereum, you can read all about it [here](https://docs.polygon.technology/docs/home/new-to-polygon). MATIC is the native token of Polygon, like Ether is to Ethereum. After you've had a chance to look at the Polygon documentation, you can read more about how to set up to use Polygon for gTrade in [Polygon ](/gtrade-leveraged-trading/setting-up-to-trade)[Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/polygon-network-setup) and [Opening and Closing a Trade](/gtrade-leveraged-trading/opening-closing-trades).

Arbitrum (specifically Arbitrum One) is a Layer 2 Optimistic Rollup for Ethereum, you can read about it [here](https://developer.arbitrum.io/intro/). Just like Ethereum Mainnet, Arbitrum uses ETH as its native token which is used to pay for gas for transactions. When you have read about what Arbitrum is, instructions on how to get started with gTrade on Arbitrum can be found in [Arbitrum Network Setup](/gtrade-leveraged-trading/setting-up-to-trade/arbitrum-network-setup) and [Opening and Closing a Trade](/gtrade-leveraged-trading/opening-closing-trades).

#### **2. What's DAI?**

DAI is a stablecoin created by [MakerDAO](https://makerdao.com/en/) and it's value is pegged 1:1 to the US dollar. It is used as collateral for trades on gTrade both on Polygon and Arbitrum. \
\
You can read all about it on the [MakerDAO](https://makerdao.com/en/) website. "*Every Dai in circulation is directly backed by excess collateral, meaning that the value of the collateral is higher than the value of the Dai debt, and all Dai transactions are publicly viewable on the Ethereum blockchain.*"

#### **3. What's GFARM2 and GNS?**

This is all explained under [GNS Token](/what-is-gains-network/gfarm2-token).

#### **4. I can't open a trade with 10 DAI - Is there a minimum position size?**

The minimum position size is 1,500 DAI on Polygon, and 7,500 DAI on Arbitrum, which is calculated by your collateral multiplied by your leverage. This means if you would like to use a position size of 10 DAI on Polygon, you should use leverage of 150x (10\*150=1,500). You can use lower leverage by using higher collateral, for instance you could use 300 DAI collateral with 5x leverage (300\*5=1,500).

#### **5. How do I set up practice mode?**

Please refer to the explanation [here](/gtrade-leveraged-trading/how-to-use-practice-mode).

#### **6. What is slippage?**

Slippage refers to the amount you would be satisfied with the price moving when opening your position. For instance, if the price were to move more than 1% while awaiting the oracle returning the price - you may be unsatisfied with that open. You can set slippage to ensure you open within the price range you are happy to, and if the price deviates from this the trade will not open.

#### **7. Why is the coin/asset I want to trade not listed?**

Coins and assets are listed when we can provide a reliable trading experience for them. This is determined based on the availability of a sufficient number of price sources as well as the trading volume and liquidity of the pair from the price sources. The [Overview page](/gtrade-leveraged-trading/overview) further describes this.

#### **8. Forex/Commodities says "Closed". Why?**

Unlike crypto markets, forex and commodities are not open 24/7. Please refer to [Forex Trading](/gtrade-leveraged-trading/asset-classes/forex), and [Commodities Trading](/gtrade-leveraged-trading/asset-classes/commodities)

#### **9. Where does the collateral go when I close for a profit/loss?**

To best understand this please refer to [gToken Vault](/liquidity-farming-pools/gtoken-vaults). In short, if you close in profit you will **always** be paid out. You are paid out from the vault which bears the risk as the main counterparty to traders. If the trade is closed at a loss, you are paid out the remaining portion of your collateral from the contract and the portion which is your loss goes to the vault. Unless you have been liquidated - in which case all collateral goes to the vault. The portion of the collateral which was your loss remains in the DAI vault to be used to pay out other traders.

#### **10. I closed my trade and don't see it in the trade history, why?**

The trade history updates every few minutes because it waits for 100 block confirmations. Updates are being worked on to make this instant.&#x20;

#### **11**. **Can I go into debt?**

**No, you cannot go into debt**. You can only lose the collateral you stake. Naturally, if your position has reached a position where it must be liquidated your loss will be all of your collateral. Otherwise, your gain or loss will be what is returned to you. **Do not put up more collateral than you could afford to lose**. Stop Losses and Take Profits can be used to help ensure you close your position where you like.

#### **12. Does profit taking close my position?**

Yes, at present your position must be closed to take profit. Partial order closure is planned for v7.

#### **13. Can I use other stablecoins as collateral?**

You cannot. Other stables can be easily converted to DAI on [quickswap.exchange](https://quickswap.exchange) or [polygon.curve.fi](https://polygon.curve.fi) for Polygon and [uniswap.exchange](https://app.uniswap.org/) or [arbitrum.curve.fi](https://arbitrum.curve.fi/) for Arbitrum.

#### **14. I have a lot of collateral. How do I know gTrade is safe?**

All trades are on-chain, and all contracts are viewable with all their functions. The contracts have been audited by [Halborn](https://halborn.com/), and their previous versions have been audited by [Certik](https://www.certik.com/), who have now done over 8 audits for Gains Network. gTrade has processed over 25 billion DAI of volume.

All contract upgrades are publicly announced in advance, audited, and contain time locks so that users can see the code base before they become active.&#x20;

All contracts can be easily viewed on Polygonscan as well as Arbiscan to confirm the functions of the platform, addresses to which can be found under [Contract Addresses](/what-is-gains-network/contract-addresses).

#### **15. What is the "0/2 Confirmations" notification that appears?**

This is the number of confirmations that happen on chain before the order appears on the front end. The order has already happened! At the moment you see "Order executed: 0/2 confirmations" the price at that moment was locked in.

The front end only shows your trade once it can be certain enough that the trade has been confirmed on-chain. As each block is 2 seconds, this is 4 seconds from when you see "Order executed".&#x20;

#### 16. Where else can I find help if I have a problem or question?

The best way is to join our [Discord](https://discord.com/invite/gains-network) server and ask in the appropriate channel (*#support, #ideas-feedback, #marketing-bizdev*). If you have a technical question, you can also open a ticket in the support section of our Discord. Please read the rules carefully and note that this ticket system is strictly for technical support. Our [Telegram](https://t.me/GainsNetwork) group is also active - post your questions and a community member or moderator will help you. Please read the chat rules. Moderators will never DM you first, please only use official channels and be wary of scammers pretending to be official staff that contact you.

#### **17. Why is price impact necessary?**

This is to allow traders to still have the option of opening in extreme, clear direction market conditions - rather than this necessitating a decrease in the maximum open interest, so traders can still take advantage of these plays. Please see more explanation [here ](/gtrade-leveraged-trading/fees-and-spread#price-impact)in the fees section and the most detailed explanation [here ](https://medium.com/gains-network/gtrade-v6-1-in-depth-b06c0b93fad1)in the medium article.

#### **18. What tokens can I use to trade?**

gTrade supports three collaterals atm: $USDC, $DAI, $WETH. You can use any of these tokens to trade any pair available for trade on the protocol.


# Chain congestion

### **What is chain congestion and how does it impact its users?**

When blockchain networks (like Arbitrum or Base) become busy, they can experience periods of **chain congestion.** This can lead to higher transaction fees (gas costs), transaction failures, or long confirmation times. While **gTrade** is designed to operate efficiently, network congestion can cause frustrating experiences that are outside our app’s control, ie:

* Gas fees rise as users compete to get their transactions included.
* Transactions may be delayed, reverted or not included at all if gas fees are too low.
* User experience degrades, especially during periods of extremely high network activity.

### How to manage chain congestion?

* **Monitor network conditions** ⇒ when platform detects unusual congestion or high gas prices on the underlying chain, gTrade will display various alerts, banners, tooltips, and notices to inform you of the situation.

<figure><img src="/files/rSBgvba7LmnFA0BEFYGV" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/qi3FTQleyqiGa7qaTf4z" alt=""><figcaption></figcaption></figure>

* **Adjust Gas Settings** ⇒ you can access this option in the footer (bottom-right corner). Consider changing to `Aggresive` setting, but pay attention to increased transaction cost (estimate costs can be found in the tooltip).

<figure><img src="/files/puNyLjlCsgqavq0IeRRq" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/xAjE6PPsCZsRO8HUOEpM" alt=""><figcaption></figcaption></figure>

* **Change Your RPC Endpoint** ⇒ an RPC in the context of blockchains is the gateway between your wallet and the blockchain. Since the default ones tend to get slow and unresponsive, oftentimes it's better to switch to a faster one, [www.chainlist.org](/#website-links) provides both a list to do this and can automate it for you.


# Arbitrum <-> Polygon Bridge

Bridge your $GNS tokens or NFTs between Arbitrum and Polygon

Our native bridge built on LayerZero, facilitates bridging GNS tokens and NFTs between Arbitrum and Polygon: <https://www.gains.trade/bridge>.

1. To bridge, select the network from which you want to bridge in the upper right corner. In the example below we are bridging from Polygon to Arbitrum, but the steps are the same regardless from which network you're bridging.&#x20;

<figure><img src="/files/2q5Fno9f4cTGioaNkUFu" alt=""><figcaption></figcaption></figure>

2. Select whether you want to bridge $GNS or an NFT from the dropdown menu, enter the amount, click approve, and then click transfer.

<figure><img src="/files/unYDGROqnyrfCqsAK5Zd" alt=""><figcaption></figcaption></figure>

3. Bridging usually takes between 20-40 minutes depending on network congestion. There is a global limit of how much can be bridged per epoch (1 epoch is 6 hours) which is 1,000,000 for $GNS and 50 for NFTs. You can see the current state of this limit above the panel.


# ERC20 Bridge (Polygon)

Bridge your GFARM2 tokens from Ethereum to Polygon and inversely.

GFARM2 tokens can be bridged on our website, on the "Bridges" page: <https://gainsnetwork.io/bridge/>.

*Note: the **GNS token only exists on Polygon and Arbitrum** for the moment. The GFARM2 bridge exists because our project started on Ethereum mainnet and later migrated to Polygon.*

### Bridge from Ethereum to Polygon

1\.   Make sure you are on the Ethereum Network. You can check this when opening the Metamask extension

![](/files/-MXbr4k2mTKRlpeSW_Z2)

2\. Click on the "APPROVE" button to allow the bridge contract to access your tokens.&#x20;

3\. Once the tokens have been approved, you can input the amount of tokens you wish to bridge over to Polygon.&#x20;

Right below the input field you can see the amount of GFARM2 tokens available to be bridged (= balance).

4\. Click on "Send". The tokens will arrive on your Polygon wallet in approximately 10 minutes.

### Bridge from Polygon to Ethereum

1\.   Make sure you are on the Polygon Network. You can check this when opening the Metamask extension

![](/files/-MYZkEI-QJWgOvnDcToX)

2\. Choose the amount of tokens you want to bridge.

3\. Burn them. Once it's done, the burn transaction hash will appear in the corresponding input.

4\. Wait for the checkpoint, click on the button to check if it has arrived. It can take a few hours.

5\. Switch to the Ethereum Mainnet network.

![](/files/-MXbr4k2mTKRlpeSW_Z2)

6\. Claim your GFARM2 tokens on Ethereum


# NFT Bridge (Polygon)

Bridge your GFARM2 NFTs from Ethereum to Polygon and inversely.

GFARM2 NFTs can be bridged on our website, on the "Bridges" page: <https://gainsnetwork.io/bridge/>.

### Before using the Ethereum to Polygon NFT Bridge

You first have to swap your NFTs to Bridgeable NFTs (if not already done). You can do so on the "Bridges" page too, at the bottom.

Simply choose the type of NFT you want to bridge (Bronze, Silver, ...), the amount, and click on "Convert".

This process must be done on the Ethereum network before bridging from Ethereum to Polygon.

### Bridge from Ethereum to Polygon

1\.   Make sure that you are on the Ethereum Network. You can check this when opening the Metamask extension

![](/files/-MXbr4k2mTKRlpeSW_Z2)

2\. Select the type and the ID of the NFT you want to bridge.

3\. Click on the "APPROVE" button to allow the bridge contract to access your NFT.&#x20;

Right below the input field you can see the number of Bridgeable NFTs  available to be bridged (= balance).

4\. Click on "Send". The NFT will arrive on your Polygon wallet in approximately 10 minutes.

### Bridge from Polygon to Ethereum

1\.   Make sure you are on the Polygon Network. You can check this when opening the Metamask extension

![](/files/-MYZkEI-QJWgOvnDcToX)

2\. Select the type and the ID of the NFT you want to bridge.

3\. Burn it. Once it's done, the burn transaction hash will appear in the corrseponding input.

4\. Wait for the checkpoint, click on the button to check if it has arrived. It can take a few hours.

5\. Switch to the Ethereum Mainnet network.

![](/files/-MXbr4k2mTKRlpeSW_Z2)

6\. Claim your NFT on Ethereum


# Integrators

Overview for dApp and contract integrations

{% hint style="danger" %}
Docs are under development and actively being updated. Please reach out to the team through Discord or Telegram with questions.&#x20;

This will speed up your integration and help the team prioritize doc improvements.
{% endhint %}

The following resources begin to detail the services and call patterns required to effectively provide information, place and manage trades for users.&#x20;

There are three separate systems:

* **Trading contracts**: Interacting with trading protocol directly
* **Backend services**: Historical data and proxy for on-chain data (active trades and live events)
* **Price feed**: Access to gTrade's Decentralized Oracle Network (DON) for accurate pricing data


# Trading Contracts

Details how to interact with trading contracts

{% hint style="info" %}
To interact with trading contracts, you should call the respective methods on the `GNSMultiCollatDiamond` contract. Each method within the facets can be accessed through this central contract, ensuring a streamlined approach to contract interactions. You can find network-specific `GNSMultiCollatDiamond` address in [Active Contracts page](https://gains-network.gitbook.io/docs-home/what-is-gains-network/contract-addresses#active-contracts)
{% endhint %}

## Addresses

For latest addresses, refer to:\
[Contract Addresses](/what-is-gains-network/contract-addresses#active-contracts)

If you are using testnet, the [Arbitrum Sepolia address ](https://louper.dev/diamond/0xd659a15812064C79E189fd950A189b15c75d3186?network=arbitrumSepolia)for `GNSMultiCollatDiamond` is:\
`0xd659a15812064C79E189fd950A189b15c75d3186`&#x20;

## Interactions

Below is a list of available actions, consisting of market & limit orders, as well as updates. Where possible, NatSpec documentation is linked to. For full reference, see [Technical Reference](/developer/technical-reference).

* Place a trade\*
* Place a limit order
* Update a trade
* Update a limit order
* Cancel a limit order
* Close a trade\*&#x20;
* Update leverage (decrease/increase)
* Increase position size
* Decrease position size

\**Requires order fulfillment. Integrators make requests, and oracles fulfill them.*

### Place a Trade

Place a trade using the following functions. Use tradeType = 0.&#x20;

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#opentrade)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#opentradenative)

If an order hasn't been fulfilled in 60 seconds, collateral can be claimed back using the timeout function:

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#opentrademarkettimeout)

### Place a Limit Order

Same as market order, but provided tradeType of 1 or 2.

\
**Limit**: To be used when you want to go long at a lower price than present, or to go short if the price reaches a higher price than present. Executes at exact price set if price reaches threshold + spread.

**Stop:** To be used when you want to go long if the price reaches a higher price than present, or to go short if the price reaches a lower price than present. You might want to use this to long a breakout, or short a breakdown. The execution price is the current market price + spread.

### Update Active Trade

Support updating take profit (TP) and stop loss (SL).&#x20;

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#updatesl)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#updatetp)

### Update Pending Limit Order

If a limit order hasn't been fulfilled yet, it can be updated

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#updateopenorder)&#x20;

### Cancel Pending Limit Order

If a limit order hasn't been fulfilled yet, it can be canceled

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#cancelopenorder)

### Close a Trade

Market close a trade

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#closetrademarket)

If the trade hasn't been closed in 60 seconds, a timeout may be initiated, allowing for another close attempt:

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#closetrademarkettimeout)

### Update Leverage

Update leverage for a trade

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#updateleverage)

### Update Position Size

Decrease position size (by decreasing collateral amount or leverage)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#decreasepositionsize)

Increase position size (by increasing collateral amount or leverage or both)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#increasepositionsize)

## Events

Events are emitted to allow off-chain services to stay updated. You can subscribe to these directly, or review the [Backend](/developer/integrators/backend)page for instructions on receiving from a WebSocket stream. It is recommended to use the backend.

**Core Events**

For opening or closing a trade: `MarketOrderInitiated` -> `MarketExecuted`

For placing a limit order: `OpenOrderPlaced`

For updating a trade: `TradeSlUpdated` or `TradeTpUpdated`

For fulfilling a limit order (SL, TP, Open limit): `LimitExecuted`

For updating leverage: `LeverageUpdateInitiated`-> `LeverageUpdateExecuted`

For  updating position size (increase): `PositionSizeUpdateInitiated`-> `PositionSizeIncreaseExecuted`

For  updating position size (decrease): `PositionSizeUpdateInitiated`-> `PositionSizeDeccreaseExecuted`

**All Lifecycle Events**

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#marketorderinitiated)&#x20;

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#triggerorderinitiated)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#openlimitupdated)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#openlimitcanceled)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#chainlinkcallbacktimeout)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#openorderplaced)

[Broken mention](broken://pages/LtzqEsvptX8Ou8ITxiuV#tradeslupdated)

[Broken mention](broken://pages/LtzqEsvptX8Ou8ITxiuV#tradetpupdated)

[Broken mention](broken://pages/6vrt4TuSolyaAcxCAXhz#marketexecuted)

[Broken mention](broken://pages/6vrt4TuSolyaAcxCAXhz#limitexecuted)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#leverageupdateinitiated)

[Broken mention](broken://pages/cchSai4zOamX0UXoCWyw#positionsizeupdateinitiated)

[Broken mention](broken://pages/6vrt4TuSolyaAcxCAXhz#leverageupdateexecuted)

[Broken mention](broken://pages/6vrt4TuSolyaAcxCAXhz#positionsizedecreaseexecuted)

[Broken mention](broken://pages/6vrt4TuSolyaAcxCAXhz#positionsizeincreaseexecuted)


# Backend

Details how to fetch trade data from off-chain services

Backend services, for the purpose of managing trades, do not provide anything that can't be fetched or listened to directly on-chain.&#x20;

It is recommended to use gTrade backends when possible however to improve resilience against RPC issues - service is optimized for uptime.

## DNS

Common DNS syntax - `backend-<network>.gains.trade`

* Arbitrum: [https://backend-arbitrum.gains.trade](https://backend-arbitrum.gains.trade/trading-variables)
* Base: <https://backend-base.gains.trade>
* Polygon: [https://backend-polygon.gains.trade](https://backend-polygon.gains.trade/trading-variables)
* Apechain: <https://backend-apechain.gains.trade>
* Sepolia: [https://backend-sepolia.gains.trade](https://backend-sepolia.gains.trade/trading-variables)
* Arbitrum WS: `wss://backend-arbitrum.gains.trade`
* Base WS: `wss://backend-base.gains.trade`
* Polygon WS: `wss://backend-polygon.gains.trade`
* Apechain WS: `wss://backend-apechain.gains.trade`
* Sepolia WS: `wss://backend-sepolia.gains.trade`

*NOTE: No auth is required for accessing REST GET endpoints and the WebSocket event stream. However, rate limiting is in place, so please fetch data only as necessary and rely on the event stream to keep your data updated.*

## Backend types&#x20;

You can find backend return types [HERE](#backend-types)

## v10 Update

As of v10, the SDK now offers normalization for both trading variables and trades.

Current version: [@gainsnetwork/sdk@1.0.0-rc1](https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.0.0-rc1)

{% hint style="info" %}
For most SDK interactions you will need `tradingVariables` object. Learn below how to fetch it and transform it to use within SDK.
{% endhint %}

#### Example: fetching and transforming trading variables

```javascript
import { transformGlobalTradingVariables } from '@gainsnetwork/sdk';

// fetch
const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`);
const tradingVariablesBackend = await tradingVariablesResponse.json();

// transform
const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend);
```

{% hint style="info" %}

#### For detailed \`/trading-variables\`  information, see "Common Endpoints" section below

{% endhint %}

#### Example: getting all trades for current address

```javascript
import { transformGlobalTradingVariables, transformGlobalTrades } from '@gainsnetwork/sdk';

// fetch
const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`);
const tradingVariablesBackend = await tradingVariablesResponse.json();

// transform 
const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend);

const { pairs, collaterals } = globalTradingVariables;

const transformedTradesForTrader = transformGlobalTrades(
    tradingVariablesBackend.allTrades, 
    pairs, 
    <current-address>, 
    collaterals
);
```

#### Example: converting [TradeContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) to [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer)

```javascript
import { transformGlobalTradingVariables, convertTradeContainer } from '@gainsnetwork/sdk';

// fetch
const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`);
const tradingVariablesBackend = await tradingVariablesResponse.json();

// transform 
const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend);

// example of single TradeContainerBackend
const someTradeBackend = tradingVariablesBackend.allTrades[0];

const tradeConverted = convertTradeContainer(someTradeBackend, globalTradingVariables.collaterals); // returns TradeContainer
```

#### Example: converting array of [FeeBackend](/developer/technical-reference/backend/backend-types#feebackend) to [FeeFrontend](/developer/technical-reference/sdk/client-types#fee)

```typescript
import { transformGlobalTradingVariables, convertFees } from '@gainsnetwork/sdk';

// fetch
const tradingVariablesResponse = await fetch(`${backendUrl}/trading-variables`);
const tradingVariablesBackend = await tradingVariablesResponse.json();

// transform 
const { globalTradingVariables } = transformGlobalTradingVariables(tradingVariablesBackend);

const fees = tradingVariablesBackend.fees; // FeeBackend[]
const feesConverted = convertFees(fees); // returns Fee[]
```

## Common Endpoints

### Trading Variables

{% hint style="warning" %}
**Depracation notice:** From 27th Oct 2025, the `allTrades` will no longer be returned through the `/trading-variables` endpoint. Please use `/open-trades/<?address>` endpoint to fetch open trades.
{% endhint %}

Provides main data necessary for opening, closing, and managing trades. Payload also contains all active trades (`allTrades`).&#x20;

Request:

`GET /trading-variables`

Response:

```ts
{
  lastRefreshed: "2024-05-20T21:07:02.133Z", // string, timestamp 
  refreshId: 6180, // number, unique identifier
  tradingState: 0, // ITradingStorage.TradingActivated, 0: Activated, 1: CloseOnly, 2: Paused
  maxGainP: 1000000, // deprecated; Maximum PNL % is no longer enforced
  marketOrdersTimeoutBlocks: 200, // number of blocks after which an unsuccessful order's collateral can be reclaimed
  globalTradeFeeParams: { // object<string, string>, breakdown of how `fees[feeIndex].totalPositionSizeFeeP` is split per category in 1e3 precision (%)
    referralFeeP: "5000",
    govFeeP: "24500",
    triggerOrderFeeP: "4000",
    gnsOtcFeeP: "56500",
    gTokenFeeP: "15000"
  },
  pairs : [ // array, containing objects for each trading pair
    {
      from: "ETH",
      to: "USD",
      spreadP: "400000000",
      groupIndex: "0",
      feeIndex: "0"
    },
    // Other trading pairs...
  ],
  groups: [ // array, containing objects for each trading group
    {
        name: "crypto",
        minLeverage: "2",
        maxLeverage: "150"
    },
    // Other trading groups...
  ],
  fees: [ // array, containing objects for each fee category
    {
      totalPositionSizeFeeP: "600000000", // % in 1e10 precision
      totalLiqCollateralFeeP: "100000000000", // % in 1e10 precision
      oraclePositionSizeFeeP: "20000000", // % in 1e10 precision
      minPositionSizeUsd: "1250000" // USD in 1e3 precision
    },
    // Other fee categories...
  ],
  pairInfos: {
    maxLeverages: [], // array, leverage overrides for each pair index for risk management
    pairDepths: [] // array, 1% depth (in USD) for current price per each pair index
    pairFactors: [] // array, protection close & cumulative factors for each pair index
  },
  collaterals: [ // array, containing objects for each supported collateral
    {
      collateralIndex: 1,
      collateral: "0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1", // string, collateral token address e.g., WETH, USDC, DAI
      symbol: "DAI",
      isActive: true,
      prices: {}, // collateral / GNS USD prices
      collateralConfig: {}, // collateral precision and decimals
      gToken: {}, // address and market cap of gToken e.g., gWETH, gUSDC, gDAI
      borrowingFees: {}, // fees for every group and pair index
      fundingFees: {}, // funding fee & skew params for each pair
      pairOis: {}, // all OIs in collateral & token size for each pair
      pairSkewDepths: {}
    },
    // Other collaterals...
  ],
  counterTradeSettings: {} // max leverage and fee discount for each pair if opened as counter trade
  sssTokenBalance: "23314652901338666091114242", // string, amount of $GNS staked in single-side staking
  sssLegacyTokenBalance: "112675327174399043872284", // string, legacy single-side staking balance
  sssRewardTokens: ["0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1", ...], // array, addresses of tokens (collaterals) distributed as rewards
  vaultClosingFeeP: "50", // number, vault closing fee percentage
  maxNegativePnlOnOpenP: 400000000000, // number, maximum negative PnL threshold upon trade opening
  blockConfirmations: 1, // number, required block confirmations
  oiWindowsSettings: { // object, settings for cumulative volume windows
      startTs: 1704401556,
      windowsDuration: 150,
      windowsCount: 4
  },
  oiWindows: [ // array, cumulative volume window objects for each trading pair
    {
      "1645": {
        oiLongUsd: "8484501256212500000000", // open longs + close shorts
        oiShortUsd: "17262712465625000000000" // close longs + open shorts
      },
      // Other windows...
    },
    // Other trading pairs...
  ], 
  feeTiers: { // object, gCredit system fee tiers
    tiers: [ // array, all possible point tiers/thresholds
      {
          feeMultiplier: "975",
          pointsThreshold: "6000000"
      },
      // Other tiers...
    ],
    multipliers: [ // array, point multipliers for each trading group (by index)
      "8000",
      // Other multipliers...
    ]
  },
  // @deprecated please use `/open-trades` to fetch open trades
  allTrades: [ // array, objects representing each active trade/order
    { 
      trade: {
        user: "0x7152BC14A1eFBfD553D1Cbc7D4E49e63Dae5A669",
        index: "0", // user's trade index
        pairIndex: "19",
        leverage: "150000", // number, leverage supports up to 3 decimals
        long: true,
        isOpen: true,
        collateralIndex: "1",
        tradeType: "2", // number, 0 - MARKET, 1 - LIMIT, 2 - STOP
        collateralAmount: "550000000000000000000",
        openPrice: "7700000000",
        tp: "8162000000",
        sl: "0",
        positionSizeToken: "0",
        isCounterTrade: false //
      },
      tradeInfo: {
        createdBlock: "192695790",
        tpLastUpdatedBlock: "192695790",
        slLastUpdatedBlock: "192695790",
        maxSlippageP: "1000",
        lastOiUpdateTs: 0,
        collateralPriceUsd: "0"
      },
      initialAccFees: {
        accPairFee: "0",
        accGroupFee: "0",
        block: "0"
      },
      liquidationParams: {}, 
      tradeFeesData: {},
      uiRealizedPnlData: {}
    },
    // Other trades...
  ],
  currentBlock: 213452457,
  currentL1Block: 19916646,
  isForexOpen: true,
  isStocksOpen: false,
  isIndicesOpen: false,
  isCommoditiesOpen: true,
}
```

### Open Trades

Returns all open trades (matches deprecated `allTrades` output from `/trading-variables` endpoint). Optionally specify trader address for filtering.

Request:&#x20;

`GET /open-trades`\
`GET /open-trades/<address>`\
\
Response:

```
// array, objects representing each active trade/order
// when <address> is provided, only open trades that match the address are returned
[ 
    { 
      trade: {
        user: "0x7152BC14A1eFBfD553D1Cbc7D4E49e63Dae5A669",
        index: "0", // user's trade index
        pairIndex: "19",
        leverage: "150000", // number, leverage supports up to 3 decimals
        long: true,
        isOpen: true,
        collateralIndex: "1",
        tradeType: "2", // number, 0 - MARKET, 1 - LIMIT, 2 - STOP
        collateralAmount: "550000000000000000000",
        openPrice: "7700000000",
        tp: "8162000000",
        sl: "0",
        positionSizeToken: "0",
        isCounterTrade: false //
      },
      tradeInfo: {
        createdBlock: "192695790",
        tpLastUpdatedBlock: "192695790",
        slLastUpdatedBlock: "192695790",
        maxSlippageP: "1000",
        lastOiUpdateTs: 0,
        collateralPriceUsd: "0"
      },
      initialAccFees: {
        accPairFee: "0",
        accGroupFee: "0",
        block: "0"
      },
      liquidationParams: {}, 
      tradeFeesData: {},
      uiRealizedPnlData: {}
    },
    // Other trades...
  ],
```

### User Trading Variables

Provides useful trader specific data, such as pending order IDs and fee tiers.

Request:

`GET /user-trading-variables/<address>`

Response:

```ts
{
    pendingMarketOrdersIds: [], 
    pendingMarketOrders: [], // array, user's market orders that are currently being processed
    feeTiers: { // object, gCredit system details
      traderInfo: {
          lastDayUpdated: 19864, // number, last recorded day on-chain
          trailingPoints: "199553481323944469547134920" // string, cumulative user's gCredit points
      },
      lastDayUpdatedPoints: "5397470676054960000000000", // string, user's on-chain points as of the last update
      inboundPoints: "5397470676054960000000000", // string, points expected to be added the next day
      outboundPoints: "0", // string, points expected to expire the next day
      expiredPoints: [] // array of strings, points for each expired day not yet recorded on-chain
    },
    collaterals: [ // array, user holdings and allowances for each collateral
      {
        balance: "5000086815959570800000", // string, user's collateral balance
        allowance: "5000086815959570800000", // string, user's collateral allowance
        decimals: 18 // number, number of decimal places for the collateral
      },
      // Other collaterals...
    ]
}
```

### Historical Trades

Provides all historical trades (open & closed) for a given address

Request:

`GET /personal-trading-history-table/<address>`

Provides all open & closed trades in last 24hrs

`GET /trading-history-24h`

Response (same for both historical endpoints):

```ts
[
  {
    date: "2024-05-21T12:04:44.000Z", // string, timestamp
    pair: "W/USD",
    address: "0x1454A3be2322B60B813713E11af36bbAF4CfeeA7",
    action: "TradeOpenedMarket", // string, type of trade action (see TradeAction type below)
    price: 0.5697297128, 
    collateralPriceUsd: 1.0003745, 
    long: 1, // number, position direction (1 for long, 0 for short)
    size: 3160.946482, // number, trade collateral
    leverage: 7, 
    pnl_net: 0, // number, net profit and loss after fees
    tx: "0x7e71dd845bb791803c16b13e4e5fe6c1a764dec4aef8205dd1f7ab8c91309aff",
    collateralIndex: 1,
    collateralDelta: 5, // number if collateral updated through partials
    leverageDelta: 20, // number if leverage updated through partials
    marketPrice: 0.5837195234 // number, market price during position size update through partials
  },
  // Other trades...
]


// Possible values for TradeAction
type TradeAction = [
  'TradeOpenedMarket', 
  'TradeClosedMarket', 
  'TradeOpenedLimit',
  'TradeClosedTP',
  'TradeClosedSL', 
  'TradeClosedLIQ'
  'TradeLeverageUpdate',
  'TradePosSizeIncrease',
  'TradePosSizeDecrease'
];
```

## Event Stream

As mentioned in [Trading Contracts](/developer/integrators/trading-contracts#events), backend event streams can serve as proxies for on-chain trade events. The stream will publish both unconfirmed and confirmed events. Unconfirmed events are published until the risk a block is reorged is negligible, at which point a confirmed event is sent. For most integrations, only confirmed events (`liveEvent`) need to be listened to.&#x20;

Backends also publish structured, post-processed events based on what on-chain event has just taken place. For example, `registerTrade` provides a full trade struct following the raw event `MarketOrderExecuted`. This is to limit how much clients need to fetch additional data.&#x20;

Structure:

```javascript
{
    name: <event name>,
    value: { <payload> },
}
```

Common event names:

* `liveEvents` - raw on-chain events. Payload is identical to on-chain event.
* `registerTrade` - trade has been registered
* `unregisterTrade` - trade has been closed
* `updateTrade` - trade SL/TP has been updated
* `updateLeverage` - trade leverage updated (collateral removed or added)
* `updatePositionSize` - trade position size updated (adding to position or partial close)
* `tradingVariables` - updated `/trading-variables` payload
* `currentBlock` - L2 block number for network
* `currentL1Block` - L1 block number for network
* `deepReorg` - Reorg has been detected - refresh data
* `new-trade-history` - New trade history document


# Contests

### Base URL

```
https://backend-global.gains.trade/api
```

### Endpoints

#### 1. List All Contests

```
GET /contests
```

**Response:**

```json
[
  {
    "id": "trickortrade",
    "start": 1729608000000,
    "end": 1732026000000,
    "chains": ["arbitrum"],
    "isActive": true
  }
]
```

***

#### 2. Get Contest Details

```
GET /contests/:id
```

**Response:**

```json
{
  "id": "trickortrade",
  "start": 1729608000000,
  "end": 1732026000000,
  "chains": ["arbitrum"],
  "isActive": true,
  "stats": {
    "totalTraders": 1247,
    "totalTrades": 8931,
    "totalPnl": 125430.5,
    "totalVolumePoints": 9847231.25,
    "top300VolumePoints": 8234192.1
  },
  "rewards": {
    "pnlAbsolute": {
      "1": 40000,
      "2": 20000,
      "3": 15000
      // ... ranks 1-50
    },
    "volume": {
      "proportional": true,
      "pool": 200000,
      "topN": 300
    }
  }
}
```

***

#### 3. Get Leaderboard

```
GET /contests/:id/leaderboard
```

**Query Parameters:**

* `sortBy` (optional): `"pnl"` or `"volume"` (default: `"pnl"`)
* `limit` (optional): Number of results to return (default: all)
* `offset` (optional): Pagination offset (default: 0)

**Example Request:**

```
GET /contests/trickortrade/leaderboard?sortBy=volume&limit=50&offset=0
```

**Response:**

```json
{
  "contestId": "trickortrade",
  "sortBy": "volume",
  "pagination": {
    "total": 1247,
    "offset": 0,
    "limit": 50,
    "count": 50,
    "hasMore": true
  },
  "leaderboard": [
    {
      "traderAddress": "0x1234...5678",
      "pnlUsd": 12450.75,
      "volumeUsd": 2450000.0,
      "volumePoints": 984532.5,
      "tradeCount": 127,
      "lastUpdated": 1729123456789,
      "rank": 1
    }
    // ... more traders
  ]
}
```

***

#### 4. Get Trader Stats

```
GET /contests/:id/leaderboard/:trader
```

**Example Request:**

```
GET /contests/trickortrade/leaderboard/0x1234567890abcdef
```

**Response:**

```json
{
  "contestId": "trickortrade",
  "trader": "0x1234567890abcdef",
  "stats": {
    "pnlUsd": 12450.75,
    "volumeUsd": 2450000.0,
    "volumePoints": 984532.5,
    "tradeCount": 127,
    "lastUpdated": 1729123456789
  },
  "rankings": {
    "pnl": 5,
    "volume": 1
  },
  "rewards": {
    "pnl": 8500,
    "volume": 23894.5,
    "total": 32394.5
  }
}
```

***

### Data Refresh Rates

60-90 seconds

### Notes

* All timestamps are in Unix milliseconds (UTC)
* Trader addresses are case-insensitive
* Volume rewards are proportionally distributed among top 300 traders
* PnL rewards are fixed amounts for top 50 traders
* `volumePoints` represents time-weighted volume (used for rankings)
* `volumeUsd` represents raw dollar volume (all opens/increases/decreases/closes)


# Price Feed

Details how to read and follow price updates

## DNS

&#x20;[https://backend-pricing.eu.gains.trade](https://backend-pricing.eu.gains.trade/charts)

*NOTE: No auth is required for accessing REST GET endpoints and the WebSocket event stream. However, rate limiting is in place, so please fetch data only as necessary and rely on the event stream to keep price data updated.*

## Common Endpoint

### Charts

Fetch current OHLCs for each pair.

`/charts`

Format:&#x20;

* Comprehensive list of OHLCs
* pairId is the index in the array (I.e. BTC/USD pairId = 0; opens\[0], highs\[0], lows\[0], closes\[0] will construct OHLC)
* `{ time, opens: [], highs: [], lows: [], closes: [] }`

## Event Stream

Subscribe for all price updates. Provides updates every 25ms.&#x20;

`wss://backend-pricing.eu.gains.trade`

* Format:
  * Array of price updates for a given 25ms interval
  * All even indexes are pairIds, odd are pair prices
  * No particular order
  * `[<pairIdX>,<pairIdXPrice>, <pairIdN>, <pairIdNPrice>, <pairIdY>, <pairIdYPrice>...]`

{% hint style="info" %}
Every \~1000ms there's single item array update. It's ping message with updated timestamp ie:`[1724244390036]`
{% endhint %}


# Guides

Examples of common use cases

## Migration guides

{% content-ref url="/pages/s0i31y1aWPmhfs4n6mYZ" %}
[v9 migration](/developer/integrators/guides/v9-migration)
{% endcontent-ref %}

## Calculating borrowing fees

{% content-ref url="/pages/av8HfAU55wYF9pyOnjFQ" %}
[Calculating borrowing fees](/developer/integrators/guides/calculating-borrowing-fees)
{% endcontent-ref %}


# Mark + Index Introduction

**tl;dr**: v3 continues to work. No immediate breaking changes. However, starting **Feb 16, 2025**, the new v4 pricing API separates mark prices (TP/SL, limits, PnL) from index prices (liquidations). Action required only if you perform liquidation calculations on volatile pairs (non-core crypto with futures feeds). Without updating, those calculations will use the wrong price.&#x20;

## Mark & Index Price Separation (v4 API)

### Overview

Starting **February 16, 2025** (tentative), gTrade introduces a new v4 format that separates **mark prices** from **index prices** to support more advanced market structures and align with industry norm.

### What Changed

<table><thead><tr><th width="142.60546875">Price Type</th><th>Description</th><th>Used For</th></tr></thead><tbody><tr><td><strong>Mark Price</strong></td><td>Price used for trade execution</td><td>TP/SL, Limit Orders, Stop Orders, PnL calculations</td></tr><tr><td><strong>Index Price</strong></td><td>Spot price, unaffected by derivatives skew</td><td><strong>Liquidations only</strong></td></tr></tbody></table>

#### How Prices Differ by Market Type

<table><thead><tr><th width="110.26171875">Type</th><th width="193.171875">Mark Price</th><th width="130.21875">Index Price</th><th>Examples</th></tr></thead><tbody><tr><td><strong>Core</strong></td><td>market (spot + skew)</td><td>spot</td><td>BTC, ETH (funding fees)</td></tr><tr><td><strong>Volatile</strong></td><td>futures</td><td>spot</td><td>Non-core crypto</td></tr><tr><td><strong>Regular</strong></td><td>spot</td><td>spot</td><td>Forex, stocks, commodities, non-core crypto w/o futures</td></tr></tbody></table>

* **Core**: Crypto with funding fees. Mark includes skew adjustment (for now clients have to calculate).
* **Volatile**: Crypto with futures feeds available. Mark sourced from futures.
* **Regular**: All other markets. Spot price used for both mark and index.

> For **Core** and **Regular** pairs, mark and index prices will be identical from gTrade endpoints. For **Volatile** pairs, they may differ significantly. **Core** will still need mark/market price calculated on the client.

***

### API Changes

#### Connection

To use the v4 API, connect to the v4 endpoint:

```
# v3 (legacy)
wss://backend-pricing.eu.gains.trade/v3

# v4 (new)
wss://backend-pricing.eu.gains.trade/v4
```

#### Message Format

**v3 (Legacy)**

```json
// Timestamp checkpoint
[1707580800000]

// Price update (flat array: [pairIndex, price, pairIndex, price, ...])
[0, 45000.50, 1, 2500.25, 2, 150.75]
```

**v4 (New)**

```json
{
  "m": [0, 45000.50, 1, 2500.25, 2, 150.75],
  "i": [0, 44998.00, 1, 2499.80, 2, 150.75],
  "t": 1707580800000
}
```

<table><thead><tr><th width="121.4296875">Field</th><th width="146.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>m</code></td><td><code>number[]</code></td><td>Mark prices as flat array <code>[pairIndex, price, ...]</code></td></tr><tr><td><code>i</code></td><td><code>number[]</code></td><td>Index prices as flat array <code>[pairIndex, price, ...]</code></td></tr><tr><td><code>t</code></td><td><code>number</code></td><td>Timestamp (milliseconds)</td></tr></tbody></table>

#### `/charts` Endpoint

The `/charts` snapshot endpoint now includes an additional `indexPrices` field alongside the existing OHLC data.

**Before:**

```json
{
  "opens": [45000.50, 2500.25, ...],
  "highs": [45100.00, 2510.00, ...],
  "lows": [44900.00, 2490.00, ...],
  "closes": [45050.00, 2505.00, ...],
  "time": 1707580800
}
```

**After:**

```json
{
  "opens": [45000.50, 2500.25, ...],
  "highs": [45100.00, 2510.00, ...],
  "lows": [44900.00, 2490.00, ...],
  "closes": [45050.00, 2505.00, ...],
  "indexPrices": [44998.00, 2499.80, ...],
  "time": 1707580800
}
```

> `opens`, `highs`, `lows`, `closes` reflect **mark prices** (as before). `indexPrices` provides the latest **index price** per pair index.

***

### SDK Changes

**`@gainsnetwork/sdk` v1.8.3** introduces:

* `corePairIndices` — exported from `constants`, provides the list of core crypto pair indices (BTC, ETH, etc.)
* `getMarketType(pairIndex)` — returns the market classification (`CORE`, `VOLATILE`, or `REGULAR`) for a given pair index

These can be used to determine which price type applies to each pair:

```typescript
import { corePairIndices, getMarketType, MARKET_TYPE } from '@gainsnetwork/sdk';

const marketType = getMarketType(pairIndex);

if (marketType === MARKET_TYPE.VOLATILE) {
  // Mark = futures, Index = spot — prices will differ
}
```

***

### Migration Guide

**Example (TypeScript):**

```typescript
socket.onmessage = (msg) => {
  const data = JSON.parse(msg.data);
  
  // Parse mark prices (for TP/SL/limits)
  const markPrices = new Map<number, number>();
  for (let i = 0; i < data.m.length; i += 2) {
    markPrices.set(data.m[i], data.m[i + 1]);
  }
  
  // Parse index prices (for liquidations)
  const indexPrices = new Map<number, number>();
  for (let i = 0; i < data.i.length; i += 2) {
    indexPrices.set(data.i[i], data.i[i + 1]);
  }
  
};
```

***

### Timeline

| Date             | Event                                                           |
| ---------------- | --------------------------------------------------------------- |
| **Feb 16, 2025** | v4 becomes recommended; index prices enabled for volatile pairs |
| **TBD**          | v3 deprecation (will be announced separately)                   |

***

### Impact of Not Updating

If you continue using v3 or don't separate mark/index prices:

* **Liquidation calculations will be incorrect** for volatile pairs, as they will use mark price instead of index price
* **TP/SL/Limit orders** are unaffected (these use mark price, which v3 provides)
* **Price display** is unaffected for most use cases

> **Recommendation:** Evaluate your integration's use of price data. If you perform liquidation-related calculations, prioritize this update. The impact depends on your exposure to volatile pairs (non core crypto pairs with separate futures markets).

***

### Questions?

Contact the Gains Network team on Discord if you have questions about the migration.


# Support Endpoints Migration

Support endpoint migration Dec 2025 -> Jan 2026

#### Endpoint Migration Table

| Category          | Previous Endpoint `backend-{chain}.gains.trade` | New Endpoint `backend-global.gains.trade`                          | Notes                                                |
| ----------------- | ----------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------- |
| **Leaderboard**   | `/leaderboard/:period`                          | `/api/leaderboard/:period?chainId={chainId}`                       | `chainId` is now a required query parameter.         |
| **Referrals**     | `/referrals/links/:link/address`                | `/api/referrals/links/:link/address`                               | Base path moved to `/api/referrals`.                 |
|                   | `/referrals/addresses/:address/link`            | `/api/referrals/addresses/:address/link`                           |                                                      |
| **Holding Rates** | `/holding-rates/:collateralIndex/:pairIndex`    | `/api/holding-rates/:collateralIndex/:pairIndex?chainId={chainId}` | `chainId` is now a required query parameter.         |
| **Stats**         | `/stats`                                        | `/api/stats?chainId={chainId}`                                     | `chainId` is now a required query parameter.         |
| **APR**           | `/apr`                                          | `/api/apr?chainId={chainId}`                                       | `chainId` is now a required query parameter.         |
| **Total Supply**  | `/total-supply`                                 | `/api/total-supply`                                                | No `chainId` required (always returns total supply). |

#### Timeline

Please migrate endpoints by Jan 12 2026


# v10.2 migration

Version 10.2 introduces a new 30-band depth system for price impact calculations, replacing the previous single `onePercentDepthUsd` value. This provides more granular control over liquidity depth at different price levels.

> **Notice:** These documents are currently in progress. For any questions or clarifications, please contact the team.

**NOTE:** Live on all networks as of 10/21

Testnet:

* Diamond contract: <https://louper.dev/diamond/0xB4F1B18b5679B42F2956dCBff3D7823A61F347C9?network=arbitrumSepolia#facets>
* Backend endpoint: `https://backend-sepolia-release.gains.trade`

SDK:&#x20;

* Version: <https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.5.0>
* Guide: <https://github.com/GainsNetwork-org/sdk/blob/feat/v10.2/docs/v10.2-migration.md>

Contracts changelog: [v10.2 Update](/developer/technical-reference/contracts/changelogs/v10.2-update)


# v10 migration

> **Notice:** These documents are currently in progress. For any questions or clarifications, please contact the team.

Current version: <https://www.npmjs.com/package/@gainsnetwork/sdk/v/1.0.0-rc12>

### v10 Changes - Overview

* New funding fees (skew-based, only on v10 positions)
* New borrowing fees v2 (alongside existing v1)
* New P\&L withdrawal feature (withdraw profits without closing)
* New counter trade type (fee discounts for improving skew)
* New skew price impact
* New market max skew limits
* Fees no longer impact position size (exact position sizes)
* Modified borrowing fees v1 (uses dynamic OI)
* Modified partial update requirements (use effective leverage)
* Modified liquidation, pnl, fees calculations
* Pre and post v10 OI stored separately
* Pre-v10 trades cannot partial add
* New accounting: TradeFeesData and UiRealizedPnlData
* New Trade fields: positionSizeToken and isCounterTrade

### Developer Notes - Overview

* SDK has been updated to support v10 more effectively than previous versions
  * Backend transforms and converters are available (fetching is still separate)
    * Transform trading variables: `transformGlobalTradingVariables`
    * Transform global trades: `transformGlobalTrades`
    * All functions expect backend types
  * Additional feature support
    * Holding fees
    * Action fees
    * Price impact
    * PnL
    * Liquidations
    * Counter trade validation
    * Effective leverage
    * Market holding rates
    * Market leverage requirements
    * Market open interest
    * Market price
  * New context builders
    * More declarative development pattern
    * SDK functions mirror contract functions. But they don't fetch data, instead rely on all data provided
    * Provide large trading variables object and context builder will prepare struct for specific functions with all expected data

### Integration Guide

NOTE: For `tradingVariables` and any trade struct (`trade`, `tradeInfo`, etc), consume from backends first: [Backend](/developer/integrators/backend#v10-update)

#### 1. New Funding Fees

Funding fees are skew-based fees that balance long/short exposure.

**Trade-Specific Funding Fees:**

```typescript
import { buildFundingContext } from "@gainsnetwork/sdk/trade/fees/fundingFees/builder";
import {
  getTradeFundingFeesCollateral,
  getAvgFundingRatePerSecondP,
} from "@gainsnetwork/sdk/trade/fees/fundingFees";

// Build funding context
const fundingContext = buildFundingContext(
  tradingVariables,
  collateralIndex,
  pairIndex,
  currentTimestamp
);

// Calculate funding fees for a trade
const fundingFees = getTradeFundingFeesCollateral(
  trade,
  currentTimestamp,
  fundingContext
);

// Get current funding rate
const { avgFundingRatePerSecondP, currentFundingRatePerSecondP } =
  getAvgFundingRatePerSecondP(fundingContext, currentTimestamp);
```

**Display helpers:**

```typescript
import {
  convertRatePerSecondToAPR,
  formatHoldingFeeRate,
} from "@gainsnetwork/sdk/markets/holdingFees";
import { fundingRateToAPR } from "@gainsnetwork/sdk/trade/fees/fundingFees/converter";

// Convert to annual percentage rate
const apr = convertRatePerSecondToAPR(ratePerSecond);
const fundingAPR = fundingRateToAPR(fundingRatePerSecond);

// Format for display (e.g., "0.25%")
const formatted = formatHoldingFeeRate(rate);
```

#### 2. New Borrowing Fees v2

Borrowing fees v2 work alongside funding fees with a simplified rate-based model.

**Context Builder & Calculation:**

```typescript
import { buildBorrowingV2Context } from "@gainsnetworks/sdk/trade/fees/borrowingV2/builder";
import { getTradeBorrowingFeesCollateral } from "@gainsnetworks/sdk/trade/fees/borrowingV2";

// Build borrowing v2 context
const borrowingV2Context = buildBorrowingV2Context(
  tradingVariables,
  collateralIndex,
  pairIndex,
  currentTimestamp
);

// Calculate borrowing fees for a trade
const borrowingFees = getTradeBorrowingFeesCollateral(
  trade,
  currentTimestamp,
  oraclePrice,
  borrowingV2Context
);
```

**Display helpers:**

```typescript
import { borrowingRateToAPR } from "@gainsnetworks/sdk/trade/fees/borrowingV2/converter";

// Convert borrowing rate to APR for display
const borrowingAPR = borrowingRateToAPR(borrowingRatePerSecond);
```

#### 3. P\&L Withdrawal Feature

Users can withdraw profits without closing their position. This maintains leverage while extracting gains.

**Contract Interaction:**

```typescript
// Direct contract call (no SDK wrapper currently)
const tx = await gnsMultiCollatDiamond.withdrawPositivePnl(
  tradeIndex,
  amountCollateral // in collateral precision (e.g., 6 decimals for USDC)
);
```

**Important behavior:** If `amountCollateral` exceeds available positive PnL, the contract will automatically withdraw only the maximum available amount (no revert).

**To withdraw all available PnL:**

```typescript
const MAX_UINT120 = BigNumber.from(2).pow(120).sub(1);
const tx = await gnsMultiCollatDiamond.withdrawPositivePnl(
  tradeIndex,
  MAX_UINT120 // Will be capped to available PnL
);
```

**Integration requirements:**

* Calculate withdrawable P\&L: `tradeValue - initialCollateral` (when positive)
* Show withdrawable amount in UI when position is in profit
* Listen for `TradePositivePnlWithdrawn` event to update UI
* Update position display after withdrawal:
  * `collateralAmount` increases
  * `positionSizeToken` remains unchanged
  * Track `pnlWithdrawnCollateral` for total withdrawn

#### 4. Counter Trade Type

Counter trades improve market balance and receive fee discounts.

**Creating a Counter Trade:**

```typescript
// When opening a trade, set the isCounterTrade flag
const tradeStruct = {
  // ... other trade parameters ...
  isCounterTrade: true, // Request counter trade discount
};

// Open trade with counter trade flag
const tx = await gnsMultiCollatDiamond.openTrade(
  tradeStruct,
  slippagePercent,
  referrer
);
```

**Note:** The contract will validate if the trade actually qualifies as a counter trade. If not, it will be rejected. If the trade size is larger than the max skew limit, it will be reduced in size but still opened.

**Pre-validation:**

```typescript
import { validateCounterTrade } from "@gainsnetworks/sdk/trade/counterTrade/validateCounterTrade";

// Check if trade qualifies as counter trade before submitting
const validation = validateCounterTrade(
  isLong,
  positionSizeCollateral,
  leverage,
  pairIndex,
  tradingVariables
);
```

**Detection (for existing trades):**

```typescript
// Check Trade struct field
const isCounterTrade = trade.isCounterTrade; // boolean field in v10 trades
```

#### 5. Skew Price Impact

Price impact based on market skew (imbalance between long/short OI).

**NOTE:** The SDK offers wrapper utilities for open and close price impact which can be used to calculate all price impact data. More in SDK convenience functions.

**Context Builder & Calculation:**

```typescript
import { buildSkewPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/skew/builder";
import { getTradeSkewPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/skew";

// Build context
const skewContext = buildSkewPriceImpactContext(
  tradingVariables,
  collateralIndex,
  pairIndex
);

// Calculate skew price impact
const skewImpact = getTradeSkewPriceImpact(
  isLong,
  oraclePrice,
  positionSizeToken,
  skewContext
);
```

**Helper functions:**

```typescript
import {
  getNetSkewToken,
  getNetSkewCollateral,
} from "@gainsnetwork/sdk/trade/priceImpact/skew";

// Get current market skew
const skewToken = getNetSkewToken(pairOiData);
const skewCollateral = getNetSkewCollateral(pairOiData, oraclePrice);
```

#### 6. Market Max Skew Limits

Markets have maximum allowed skew to prevent excessive imbalance.

**Check skew using computeOiValues:**

```typescript
import { computeOiValues } from "@gainsnetworks/sdk/markets/oi/converter";

// Compute current OI values including skew
const { skewToken } = computeOiValues(
  pairOi,
  oraclePrice / collateralPriceUsd // Convert to token price in collateral
);

// Get max skew from trading variables
const maxSkewCollateral =
  tradingVariables.pairs[pairIndex]?.params?.maxSkewCollateral;

// Convert skewToken to collateral for comparison
const skewCollateral = Math.abs(skewToken) * (oraclePrice / collateralPriceUsd);
const skewExceeded = skewCollateral > maxSkewCollateral;
```

**Note:** For counter trade validation and position sizing, use `validateCounterTrade` (see section 5).

#### 7. Effective Leverage in Partial Updates

Partial position updates now validate against effective leverage (accounts for unrealized P\&L).

**Calculation:**

```typescript
import { getEffectiveLeverage } from "@gainsnetworks/sdk/trade/effectiveLeverage";

// Calculate effective leverage
const effectiveLeverage = getEffectiveLeverage(
  trade.leverage,
  trade.collateralAmount,
  pnlCollateral
);
```

**Validation Requirements:**

**For Position Increases (Partial Add):**

* Effective leverage must not exceed `pairMaxLeverage`
* Counter trades must not exceed `pairCounterTradeMaxLeverage`
* Adjusted initial leverage must be between 0.1x and max uint24 (\~16,777x)
* Pre-v10 trades cannot partial add

**For Position Decreases (Partial Close):**

* No effective leverage maximum check
* Only validates adjusted initial leverage (≥ 0.1x)

**For Leverage Increases:**

* Same as position increases - effective leverage validated

**For Leverage Decreases (Add Collateral):**

* Same as position decreases - no effective leverage check

```typescript
// Example validation
const maxLeverage = isCounterTrade
  ? tradingVariables.pairs[pairIndex].maxLeverageCounterTrade
  : tradingVariables.pairs[pairIndex].maxLeverage;

const isValid = effectiveLeverage <= maxLeverage;
const MIN_LEVERAGE = 0.1; // 0.1x minimum
```

#### 8. Modified Borrowing Fees v1

Borrowing fees v1 now use dynamic OI (position size adjusted by current price vs entry price).

**Context Builder & Calculation:**

```typescript
import { buildBorrowingV1Context } from "@gainsnetworks/sdk/trade/fees/borrowing/builder";
import { getBorrowingFee } from "@gainsnetworks/sdk/trade/fees/borrowing";

// Build borrowing v1 context
const borrowingV1Context = buildBorrowingV1Context(
  tradingVariables,
  collateralIndex,
  currentBlock
);

// Calculate borrowing fee for a trade
const borrowingFee = getBorrowingFee(
  positionSizeCollateral,
  pairIndex,
  isLong,
  initialAccFees,
  currentPairPrice,
  borrowingV1Context
);
```

**Utility functions:**

```typescript
import { borrowingFeeUtils } from "@gainsnetworks/sdk/trade/fees/borrowing";

// Get pending accumulated fees for a pair
const pendingFees = borrowingFeeUtils.getPairPendingAccFees(
  pairs,
  pairGroups,
  groups,
  initialAccFees,
  pairIndex,
  currentBlock,
  feePerBlockCaps
);

// Check if within max group OI
const withinLimit = borrowingFeeUtils.withinMaxGroupOi(
  pairs,
  pairGroups,
  groups,
  positionSizeCollateral,
  pairIndex,
  isLong
);
```

#### 9. Modified Liquidation Calculations

Liquidation now accounts for pending fees and realized P\&L.

**Context Builder & Calculation:**

```typescript
import { buildLiquidationPriceContext } from "@gainsnetwork/sdk/trade/liquidation/builder";
import { getLiquidationPrice } from "@gainsnetwork/sdk/trade/liquidation";

// Build comprehensive context
const liquidationContext = buildLiquidationPriceContext(
  tradingVariables,
  tradeContainer,
  {
    currentBlock,
    currentTimestamp,
    currentPairPrice,
    spreadP,
    traderFeeMultiplier,
    userPriceImpact,
  }
);

// Calculate liquidation price
const liqPrice = getLiquidationPrice(trade, liquidationContext);
```

**Additional functions:**

```typescript
import { getLiquidationPriceAfterPositionUpdate } from "@gainsnetwork/sdk/trade/liquidation";

// Calculate after position update
const newLiqPrice = getLiquidationPriceAfterPositionUpdate(
  existingTrade,
  existingLiquidationContext,
  newCollateralAmount,
  newLeverage
);
```

#### 10. Modified PnL Calculations

Comprehensive PnL includes all v10 components: funding fees, borrowing fees, and realized P\&L.

**Context Builder & Calculation:**

```typescript
import { buildComprehensivePnlContext } from "@gainsnetwork/sdk/trade/pnl/builder";
import { getComprehensivePnl } from "@gainsnetwork/sdk/trade/pnl";

// Build context
const pnlContext = buildComprehensivePnlContext(
  tradingVariables,
  tradeContainer,
  {
    currentBlock,
    currentTimestamp,
    traderFeeMultiplier,
  }
);

// Calculate comprehensive PnL
const pnl = getComprehensivePnl(
  trade,
  marketPrice,
  executionPrice, // price after spreads/impacts
  tradeInfo,
  pnlContext
);
```

**Helper functions:**

```typescript
import { getPnlPercent, getTradeValue } from "@gainsnetwork/sdk/trade/pnl";

// Calculate PnL percentage
const pnlPercent = getPnlPercent(openPrice, currentPrice, isLong, leverage);

// Get trade value (collateral + PnL)
const tradeValue = getTradeValue(collateralAmount, pnlCollateral, 0); // pass 0 for raw trade value calculation
```

#### 11. New Trade Fields

v10 trades have additional fields that must be parsed and stored.

**New fields in Trade struct:**

```typescript
interface Trade {
  // ... existing fields ...
  positionSizeToken: bigint; // Position size in token units (1e18 precision)
  isCounterTrade: boolean; // Whether trade qualified for counter trade discount
}
```

#### 12. V10 OI Tracking

OI is tracked separately for pre-v10 and post-v10 trades.

**OI Functions:**

```typescript
import {
  getPairTotalOisCollateral,
  getPairTotalOisDynamicCollateral,
  getPairV10OiTokenSkewCollateral,
  getPairV10OiDynamicSkewCollateral,
} from "@gainsnetworks/sdk/markets/oi";

// Get total OI (pre-v10 only)
const staticOI = getPairTotalOisCollateral(pairOi);

// Get dynamic OI (pre-v10 + v10 adjusted by price)
const dynamicOI = getPairTotalOisDynamicCollateral(pairOi, oraclePrice);

// Get v10 skew in collateral
const skewCollateral = getPairV10OiTokenSkewCollateral(pairOi, oraclePrice);

// Get v10 dynamic skew
const dynamicSkew = getPairV10OiDynamicSkewCollateral(pairOi, oraclePrice);
```

**Comprehensive OI Values:**

```typescript
import { computeOiValues } from "@gainsnetwork/sdk/markets/oi/converter";

// Get all computed OI values at once
const oiValues = computeOiValues(
  pairOi,
  oraclePrice / collateralPriceUsd // Convert to token price in collateral
);
```

**Important notes:**

* Funding fees only apply to v10 OI
* Skew calculations use v10 OI only
* Max OI checks use combined OI (pre-v10 + v10)
* Counter trade validation uses v10 skew

### Market Price Concept

Market price is a v10 feature that applies to markets with funding fees and skew price impact. It represents the oracle price adjusted for current market skew.

**Calculate Market Price:**

```typescript
import { getCurrentMarketPrice } from "@gainsnetworks/sdk/markets/price/marketPrice";
import { buildMarketPriceContext } from "@gainsnetworks/sdk/markets/price/builder";

// Build context for market price calculation
const marketPriceContext = buildMarketPriceContext(tradingVariables, pairIndex);

// Calculate market price from oracle price
const { marketPrice, skewImpactP } = getCurrentMarketPrice(
  pairIndex,
  oraclePrice,
  marketPriceContext
);
```

### SDK Wrapper Functions

The SDK provides high-level wrapper functions that combine multiple calculations for common operations.

#### Price Impact

**Opening a Trade:**

```typescript
import { getTradeOpeningPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/open";
import { buildTradeOpeningPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/open/builder";

// Build context with all required data
const openContext = buildTradeOpeningPriceImpactContext(
  tradingVariables,
  collateralIndex,
  pairIndex,
  currentBlock
);

// Calculate total price impact and execution price
const openImpact = getTradeOpeningPriceImpact(
  oraclePrice, // Always pass oracle price
  isLong,
  positionSizeCollateral,
  leverage,
  openContext
);
```

**Understanding Price Impact Results:**

```typescript
// The function returns multiple price impact values:
const {
  priceAfterImpact, // Final execution price
  totalPriceImpactP, // Total impact from oracle price
  totalPriceImpactPFromMarketPrice, // Total impact from market price
  baseSkewPriceImpactP, // Market skew before trade
  tradeSkewPriceImpactP, // Additional skew from this trade
  totalSkewPriceImpactP, // Total skew impact (base + trade)
} = openImpact;

// For UI display:
// If showing market price: use totalPriceImpactPFromMarketPrice
// If showing oracle price: use totalPriceImpactP
```

**Closing a Trade:**

```typescript
import { getTradeClosingPriceImpact } from "@gainsnetwork/sdk/trade/priceImpact/close";
import { buildTradeClosingPriceImpactContext } from "@gainsnetwork/sdk/trade/priceImpact/close/builder";

// Build context
const closeContext = buildTradeClosingPriceImpactContext(
  tradingVariables,
  tradeContainer,
  currentBlock
);

// Calculate price impact for closing
const closeImpact = getTradeClosingPriceImpact(
  trade,
  oraclePrice, // Always pass oracle price
  closeContext
);

// Similar to opening, returns multiple impact values
const {
  priceAfterImpact,
  tradeValueCollateral,
  totalPriceImpactP, // From oracle price
  totalPriceImpactPFromMarketPrice, // From market price
  // ... other impact components
} = closeImpact;
```

#### Action Fees (Trading Fees)

**Calculate Total Trading Fees:**

```typescript
import { getTotalTradeFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading";
import { buildTradingFeesContext } from "@gainsnetwork/sdk/trade/fees/trading/builder";

// Build context
const feesContext = buildTradingFeesContext(
  tradingVariables,
  collateralIndex,
  pairIndex
);

// Calculate total fees
const totalFees = getTotalTradeFeesCollateral(
  positionSizeCollateral,
  isCounterTrade,
  tradeTier,
  feesContext
);
```

**Get Detailed Fee Breakdown:**

```typescript
import { getTradeFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading";

// Get breakdown of all fee components
const feeBreakdown = getTradeFeesCollateral(
  positionSizeCollateral,
  pairOpenFeeP,
  tradeTierMultiplier,
  referralFeeP,
  pairTriggerOrderFeeP,
  pairOtcFeeP,
  collateralPrecision
);
// Returns: referralFees, govFees, triggerFees, gnsOtcFees, gTokenFees
```

**Calculate Pending Holding Fees:**

```typescript
import { getTradePendingHoldingFeesCollateral } from "@gainsnetwork/sdk/trade/fees/trading";

// Calculate all accumulated holding fees
const holdingFees = getTradePendingHoldingFeesCollateral(
  trade,
  currentBlock,
  currentTimestamp,
  oraclePrice,
  collateralPrecision,
  holdingFeesContext // combines funding + borrowing contexts
);
```

### Summary

The SDK provides all necessary functions to integrate v10 features. Key patterns:

1. **Use Context Builders**: Most complex calculations require a context object built from trading variables
2. **Transform Backend Data**: Use `transformGlobalTradingVariables` and `transformGlobalTrades` before passing to SDK functions
3. **Handle Pre-v10 Trades**: Check `trade.contractsVersion` to determine if a trade uses v10 features
4. **Display Market Rates**: Use functions in "Current Market Rates" section for market-wide statistics


# v9 migration

For v9, external devs and partners need to adjust the updated  [getLiquidationPrice](https://github.com/GainsNetwork-org/sdk/blob/35469e835db5a3de31b395bd557eeb3953df1d15/src/trade/liquidation.ts#L9C14-L9C33) function from the [Gains Network SDK](https://github.com/GainsNetwork-org/sdk) by removing the `tradeInfo` param and adding the `fee: Fee` param.

```typescript
export const getLiquidationPrice = (
  trade: Trade,
  fee: Fee,
  initialAccFees: BorrowingFee.InitialAccFees,
  context: GetBorrowingFeeContext
):
```

```typescript
export type Fee = {
  openFeeP: number;
  closeFeeP: number;
  minPositionSizeUsd: number;
  triggerOrderFeeP: number;
};
```

Fetching openFeeP from method&#x20;

[Broken mention](broken://pages/FJiPWdH0rvellwZli8FO#pairopenfeep)

Fetching closeFeeP from method

[Broken mention](broken://pages/FJiPWdH0rvellwZli8FO#pairclosefeep)

Fetching minPositionSizeUsd: number;

[Broken mention](broken://pages/FJiPWdH0rvellwZli8FO#pairminpositionsizeusd)

Fetching triggerOrderFeeP

[Broken mention](broken://pages/FJiPWdH0rvellwZli8FO#pairtriggerorderfeep)


# Calculating borrowing fees

Learn how to calculate trader's borrowing fees

## Overview

* Borrowing fees are paid only by one side (either longs or shorts) which is decided by current open interest (higher OI pays the fee)
* Each pair is part of a group, meaning that borrowing fee should be calculated for pair and pair's group and the higher of two should be charged (never both)
* Borrowing fee is charged on trader's position size (collateral \* leverage)

## Borrowing fee per block

The formula for borrowing fee per block is:

{% hint style="info" %}

```
feePerBlock * (abs(longOi - shortOi) / maxOi) ** feeExponent
```

{% endhint %}

### *Example:*

Let's calculate the borrowing fee for **ENA/USD** pair (`pairIndex` is `219`) against USDC collateral (`collateralIndex` is `3`)

#### 1) Fetching Open Interest and Fees

Access current open interests and fees for given collateral and pair index via [`trading-variables`](/developer/integrators/backend#trading-variables) endpoint described [**here**](/developer/integrators/backend#trading-variables)**.**&#x20;

#### 2) Calculating Pair Borrowing Fees

To calculate ENA/USD borrowing fees, we use the following object retrieved from Step 1:

{% code overflow="wrap" %}

```javascript
tradingVariables.collaterals[2].borrowingFees.pairs[219] // collaterals[2] because its 0 indexed
```

{% endcode %}

```javascript
{
    "oi": {
        "long": "228761980790000", // 1e10
        "short": "59904000000000", // 1e10
        "max": "8806660000000000" // 1e10
    },
    "feePerBlock": "100236", // 1e10
    "feeExponent": "1",
    "groups": [
        {
            "groupIndex": "2",
            ...
        }
    ],
    ...
}
```

With these values, we can calculate the pair's borrowing fee (per block):

```javascript
feePerBlock = 0.0000100236
longOi = 22876.198079
shortOi = 5990.4
maxOi = 880666

pairFeePerBlock = 0.0000100236 * Math.abs(22876.198079 - 5990.4) / 880666 ** 1 = 1.9219146149012726e-7
```

#### 3) Calculating Group Borrowing Fees

Now we need to do the same for group fee, reading the `groupIndex` from the same `trading-variables` response (for this example, `groupIndex` is `2`). The process is the same as for calculating pair fees, using `groups` values of `borrowingFees`:

```javascript
tradingVariables.collaterals[2].borrowingFees.groups[2]
```

```javascript
{
    "oi": {
        "long": "7704464978990000", // 1e10
        "short": "1841270854980000", // 1e10
        "max": "50906510000000000" // 1e10
    },
    "feePerBlock": "16871", // 1e10
    "feeExponent": "1"
    ...
}
```

Therefore, the group's borrowing fee (per block) will be:

```javascript
feePerBlock = 0.0000016871
longOi = 770446.497899
shortOi = 184127.085498
maxOi = 5090651

groupFeePerBlock = 0.0000016871 * Math.abs(770446.497899 - 184127.085498) / 5090651 ** 1 = 1.9431296324610092e-7
```

In this example, `groupFeePairBlock`is greater than `pairFeePerBlok` (`1.9431296324610092e-7 > 1.9219146149012726e-7`) so `groupFeePairBlock` is the effective `feePerBlock`.

#### 4) Estimating Borrowing fee per hour

To estimate the hourly paid fee, we need to multiply the number of blocks per hour `feePerBlock`.

```javascript
feePerHour = blocksPerHour * Math.max(pairFeePerBlock, groupFeePerBlock)
```

For this example, on **Arbitrum** (12000 blocks per hour), the estimated borrowing fee per hour is:

{% code overflow="wrap" %}

```javascript
feePerHour = 12000 * Math.max(1.9219146149012726e-7, 1.9431296324610092e-7) // 0.002331755558953211% Borrowing (L) 
```

{% endcode %}

Which corresponds to **gTrade**'s UI:

<figure><img src="/files/J01QQSqITaxkLo93Jgq7" alt=""><figcaption></figcaption></figure>


# Calculating liquidation price

Learn how to calculate any trade's liquidation price

> *Note: This guide works on **Arbitrum Sepolia** and requires **exact** beta SDK version of 0.2.12-rc15*

To calculate liquidation price, we need to use [SDK's](/developer/technical-reference/sdk) `getLiquidationPrice()` function.

{% hint style="info" %}
getLiquidationPrice: (trade: [Trade](/developer/technical-reference/sdk/client-types#trade), fee: [Fee](/developer/technical-reference/sdk/client-types#fee), initialAccFees: [InitialAccFees](/developer/technical-reference/sdk/client-types#initialaccfees), context: GetLiquidationPriceContext) => number;
{% endhint %}

## TradeContainer

To calculate trade's liquidation price, we need to find a trade and its [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer) first. TradeContainer is unique object per single trade and is containing all its information.&#x20;

By inspecting `allTrades` of backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) response, we're able to find all open trades & orders (each represented by single, unique [TradingContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) object). Lets pick last market trade (`trade.type` = 0 ) at time of writing this guide, which is:

```typescript
{
    "trade": {
        "user": "0xa110CC27a19f6853e9Aa8Bb8e2C603D7b02ea2df",
        "index": "350",
        "pairIndex": "103",
        "leverage": "45000",
        "long": true,
        "isOpen": true,
        "collateralIndex": "3",
        "tradeType": "0",
        "collateralAmount": "1938800000",
        "openPrice": "47781798348",
        "tp": "57338158017",
        "sl": "0"
    },
    "tradeInfo": {
        "createdBlock": "72595369",
        "tpLastUpdatedBlock": "72595369",
        "slLastUpdatedBlock": "72595369",
        "maxSlippageP": "0",
        "lastOiUpdateTs": "0",
        "collateralPriceUsd": "0",
        "contractsVersion": "1",
        "lastPosIncreaseBlock": "72595369"
    },
    "liquidationParams": {
        "maxLiqSpreadP": "500000000",
        "startLiqThresholdP": "900000000000",
        "endLiqThresholdP": "650000000000",
        "startLeverage": "25000",
        "endLeverage": "60000"
    },
    "initialAccFees": {
        "accPairFee": "1461579560",
        "accGroupFee": "828216663",
        "block": "72595369"
    }
}
```

This response is of [TradeContainerBackend](/developer/technical-reference/backend/backend-types#tradecontainerbackend) type, therefore we need to properly convert it to [TradeContainer](/developer/technical-reference/sdk/client-types#tradecontainer) type first (SDK uses [client types](/developer/technical-reference/sdk/client-types)). Converted and normalised trade will look like this:

```typescript
{
    "trade": {
        "user": "0xa110CC27a19f6853e9Aa8Bb8e2C603D7b02ea2df",
        "index": 350,
        "pairIndex": 103,
        "leverage": 45,
        "long": true,
        "isOpen": true,
        "collateralIndex": 3,
        "tradeType": 0,
        "collateralAmount": 1938.8,
        "openPrice": 4.7781798348,
        "sl": 0,
        "tp": 5.7338158017
    },
    "tradeInfo": {
        "createdBlock": 72595369,
        "tpLastUpdatedBlock": 72595369,
        "slLastUpdatedBlock": 72595369,
        "maxSlippageP": 1,
        "lastOiUpdateTs": 1724162804,
        "collateralPriceUsd": 1.0000162,
        "contractsVersion": 1,
        "lastPosIncreaseBlock": 72595369
    },
    "liquidationParams": {
        "maxLiqSpreadP": 0.0005,
        "startLiqThresholdP": 0.9,
        "endLiqThresholdP": 0.65,
        "startLeverage": 25,
        "endLeverage": 60
    },
    "initialAccFees": {
        "accPairFee": 0.146157956,
        "accGroupFee": 0.0828216663,
        "block": 72595369
    }
}
```

Respective `trade` and `initialAccFees` objects will be used as first and third arguments of SDK's `getLiquidationPrice()` while `liquidationParams` and `tradeInfo` will be helpful when crafting fourth argument (`context`).

## Fee

Lets focus on second `getLiquidationPrice()` argument now, which is [Fee](/developer/technical-reference/sdk/client-types#fee).

To find proper [Fee](/developer/technical-reference/sdk/client-types#fee) object, we need to compute `feeIndex` for given trade first. By calling backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) we're getting `pairs` and `fees` arrays.&#x20;

{% hint style="info" %}
Remember that backend values should be normalised, see [Pair](/developer/technical-reference/sdk/client-types#pair) vs [PairBackend](/developer/technical-reference/backend/backend-types#pairbackend) and [Fee](/developer/technical-reference/sdk/client-types#fee) vs [FeeBackend](/developer/technical-reference/backend/backend-types#feebackend)
{% endhint %}

With `pairs` and trade's `pairIndex` we compute `feeIndex`:

> pairs\[trade.pairIndex].feeIndex

Now we are able to find our [Fee](/developer/technical-reference/sdk/client-types#fee) by simply accessing `fees[feeIndex]`. Resulting object should look similar to this:

```typescript
{
    "openFeeP": 0.0003,
    "closeFeeP": 0.0006,
    "minPositionSizeUsd": 10000,
    "triggerOrderFeeP": 0.0002
}
```

## Context

We've now covered 3 arguments and are left with last one, the `GetLiquidationPriceContext`.

There are few context parameters that we can pass here. All of them are coming from backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) endpoint or [`TradeContainer`](#tradecontainer) discussed above.

```typescript
type GetLiquidationPriceContext = {
    currentBlock: number;
    groups: BorrowingFeeGroup[];
    pairs: BorrowingFeePair[];
    liquidationParams: LiquidationParams | undefined;
    pairSpreadP: number | undefined;
    collateralPriceUsd: number | undefined;
    contractsVersion: ContractsVersion | undefined;
}
```

`currentBlock`

Its current block of underlying network. Use any valid block or backend's [`/trading-variables`](/developer/integrators/backend#trading-variables) response:

> tradingVariables.currentBlock

`groups` and `pairs`

To get `groups` and `pairs` we need to inspect `collaterals` backend [`/trading-variables`](/developer/integrators/backend#trading-variables) response. It is an array of objects corresponding to each supported collateral. Use `trade.collateralIndex` to select proper collateral object, then access its `borrowingFees:`

> tradingVariables.collaterals\[trade.collateralIndex - 1].borrowingFees

{% hint style="info" %}
Remember that backend values should be normalised, see [PairParamsBorrowingFees](/developer/technical-reference/sdk/client-types#pairparamsborrowingfees) vs [PairParamsBorrowingFeesBackend](/developer/technical-reference/backend/backend-types#pairparamsborrowingfeesbackend)
{% endhint %}

`liquidationParams`

Available directly on [TradeContainer](#tradecontainer)&#x20;

`pairSpreadP`

To get `pairSpreadP` inspect `pairs` key of backends `/trading-variables` response. It is an array of objects corresponding to each pair. Use `trade.pairIndex` to select proper pair:

> tradingVariables.pairs\[trade.pairIndex].spreadP

{% hint style="info" %}
Should be normalised, see [Pair](/developer/technical-reference/sdk/client-types#pair) vs [PairBackend](/developer/technical-reference/backend/backend-types#pairbackend)&#x20;
{% endhint %}

`collateralPriceUsd`

Its similar to getting `groups` and `pairs` but select `prices` key after accessing proper `collaterals` entry:

> tradingVariables.collaterals\[trade.collateralIndex - 1].prices.collateralPriceUsd

`contractsVersion`

Available on [TradeContainer](#tradecontainer):

> tradeInfo.contractsVersion

At the end, the context passed to `getLiquidationPrice()` should look similar to this:

```typescript
{
    "currentBlock": 72867071,
    "groups": [...],
    "pairs": [...],
    "liquidationParams": {
        "maxLiqSpreadP": 0.0005,
        "startLiqThresholdP": 0.9,
        "endLiqThresholdP": 0.65,
        "startLeverage": 25,
        "endLeverage": 60
    },
    "pairSpreadP": 0,
    "collateralPriceUsd": 1.0000328,
    "contractsVersion": 1
}
```

## Calculate liquidation price

Wrapping all of the above, we should pass `trade`, `fee`, `initialAccFees` and `context` to SDK's `getLiquidationPrice()`. This should return single, float number. Per example above the return liquidation price is:

`4.702126243307295`

which matches gTrade's UI:

<div align="left"><figure><img src="/files/CHKR6fADNZbXVOPjW1Ly" alt=""><figcaption></figcaption></figure></div>


# Backend Endpoint Refactor

From the 27th of October 2025, in an effort to reduce the size of payloads returned, the `/trading-variables` endpoint will omit `allTrades`. Please use the new, already available, endpoints to fetch open trades and a leaner version of trading variables.\
\
**TLDR**:

* `GET /trading-variables` <sup><mark style="color:$warning;">partially deprecated<mark style="color:$warning;"></sup>
  * Currently returns the `allTrades` property.
  * <mark style="color:$danger;">`allTrades`</mark> <mark style="color:$danger;"></mark><mark style="color:$danger;">property will be deprecated on 10/27/2025.</mark>
* `GET /trading-variables/all` <sup><mark style="color:$success;">new<mark style="color:$success;"></sup>
  * Returns trading variables with an empty `allTrades` property.
  * Significantly reduces payload size and speeds up request time.
* `GET /open-trades/<?address>` <sup><mark style="color:$success;">new<mark style="color:$success;"></sup>&#x20;
  * Returns an array of open trades. Trade container types remain the same.&#x20;
  * Replaces `allTrades` payload from deprecated `/trading-variables` endpoint.&#x20;
  * *Optional:* provide an address to filter returned trades. Significantly reduces payload size.
    * <mark style="color:$warning;">Important</mark>: If provided, `address` **MUST** be checksummed.


# History Endpoints Migration

NOTE: Old endpoints will be fully removed Mon Dec 1. Please migrate to new endpoints.

## Backend Global API Migration Guide

### Overview

The trading history endpoints have been migrated from `backend-[network]` service to the new `backend-global` endpoints with improved caching, pagination, and new statistics endpoints.

**Base URL Change:**

* **Old:** `https://backend-[network].gains.trade`
* **New:** `https://backend-global.gains.trade`

***

### Endpoint Migration Map

#### 24-Hour Trading History

<table><thead><tr><th width="265.76171875">Old Endpoint</th><th>New Endpoint</th><th>Changes</th></tr></thead><tbody><tr><td><code>GET /trading-history-24h</code></td><td><code>GET /api/trading-history/24h?chainId={id}</code></td><td>Path prefix added, chainId support</td></tr></tbody></table>

**Migration:**

```diff
- GET https://backend-arbitrum.gains.trade/trading-history-24h
+ GET https://backend-global.gains.trade/api/trading-history/24h?chainId=42161
```

**Response Format:** Unchanged (returns array of trades)

***

#### Personal Trading History

**Main History Endpoint**

<table><thead><tr><th width="232.66796875">Old Endpoint</th><th width="287.69140625">New Endpoint</th><th>Changes</th></tr></thead><tbody><tr><td><code>GET /personal-trading-history-table/:address</code></td><td><code>GET /api/personal-trading-history/:address?chainId=X</code></td><td>Path renamed, cursor-based pagination, limits</td></tr></tbody></table>

**Migration:**

```diff
- GET https://backend.gains.trade/personal-trading-history-table/0x123...
+ GET https://backend-global.gains.trade/api/personal-trading-history/0x123...?chainId=42161&limit=50
```

**Response Format:**

```json
{
  "data": [...],           // Array of trades (same as before)
  "pagination": {
    "hasMore": true,       // Whether more data available
    "nextCursor": 123456,  // Cursor for next page (null if no more)
    "limit": 50           // Limit used for this request, no higher than 200
  }
}
```

**Pagination:**

* **Old:** No offset
* **New:** Cursor-based (`?cursor=123456`)

**To fetch next page:**

```javascript
// Old (offset-based)
const page1 = await fetch(
  "/personal-trading-history-table/0x123?offset=0&limit=50"
);
const page2 = await fetch(
  "/personal-trading-history-table/0x123?offset=50&limit=50"
);

// New (cursor-based)
const page1 = await fetch("/api/personal-trading-history/0x123?limit=50");
const { data, pagination } = await page1.json();

if (pagination.hasMore) {
  const page2 = await fetch(
    `/api/personal-trading-history/0x123?cursor=${pagination.nextCursor}&limit=50`
  );
}
```

**Query Parameters:**

* `chainId` (required): Chain ID
* `cursor` (optional): Pagination cursor (omit for first page)
* `limit` (optional): Max trades per request (default: 50, max: 1000)
* `startDate` (optional): ISO 8601 date filter
* `endDate` (optional): ISO 8601 date filter
* `pair` (optional): Trading pair filter
* `action` (optional): Action type filter

***

**Statistics Endpoint (NEW)**

**New endpoint for trader statistics:**

```http
GET /api/personal-trading-history/:address/stats?chainId={id}
```

**Response:**

```json
{
  "totalVolume": 123456.78,
  "totalTrades": 42,
  "winRate": 65.5,
  "thirtyDayVolume": 12345.67
}
```

**Use case:** Get all-time stats without fetching full trade history.

***

**Batch Statistics Endpoint (NEW)**

**New endpoint for batched trader statistics:**

```http
POST /api/personal-trading-history/stats
Content-Type: application/json

{
  "addresses": ["0x123...", "0x456..."],
  "chainId": 42161
}
```

**Response:**

```json
{
  "0x123...": {
      "totalVolume": 123456.78,
      "totalTrades": 42,
      "winRate": 65.5,
      "thirtyDayVolume": 12345.67
  },
  "0x456...": {
      "totalVolume": 67890.12,
      "totalTrades": 12,
      "winRate": 40.13,
      "thirtyDayVolume": 2345.67
  }
}
```

**Use case:** Get all-time stats without fetching full trade history.

***

**Batch Trading History Endpoint (NEW)**

**New endpoint for fetching multiple addresses:**

```http
POST /api/personal-trading-history/batch
Content-Type: application/json

{
  "addresses": ["0x123...", "0x456..."],
  "chainId": 42161,
  "limit": 50,
  "cursors": {"0x123...": 123, "0x456...": null}
}
```

**Response:**

```json
{
  "0x123...": {
    "data": [...],
    "pagination": { "hasMore": true, "nextCursor": 123, "limit": 50 }
  },
  "0x456...": {
    "data": [...],
    "pagination": { "hasMore": false, "nextCursor": null, "limit": 50 }
  }
}
```

***

### Deprecated Endpoints

#### ⚠️ DO NOT USE

| Endpoint                                       | Status         | Replacement                                  |
| ---------------------------------------------- | -------------- | -------------------------------------------- |
| `GET /personal-trading-history/:address`       | **DEPRECATED** | Use `/api/personal-trading-history/:address` |
| `GET /personal-trading-history-table/:address` | **DEPRECATED** | Use `/api/personal-trading-history/:address` |
| `GET /trading-history-24h`                     | **DEPRECATED** | Use `/api/trading-history/24h`               |

**Note:** The old `/personal-trading-history/:address` (without `-table`) returned a flat array and is now deprecated. Use the new cursor-based endpoint instead.

***

### Migration Checklist

* [ ] Update base URL from `backend.gains.trade` → `backend-global.gains.trade`
* [ ] Add `/api` prefix to all endpoints
* [ ] Rename `/personal-trading-history-table` → `/personal-trading-history`
* [ ] Add cursor pagination
* [ ] Update response parsing to handle `{ data, pagination }` structure
* [ ] Use `/stats` endpoint if only statistics are needed

***

### Support

For questions or issues with migration, please contact the Gains Network development team.


# Technical Reference

[Contracts](/developer/technical-reference/contracts)

[Backend](/developer/technical-reference/backend)

[SDK](/developer/technical-reference/sdk)


# Contracts

Natspec for gTrade's Contracts

**Please refer to** [Changelogs](/developer/technical-reference/contracts/changelogs) **for a contract changelog breakdown for each new release.**


# Changelogs


# v10.2 Update

## Changelog

### Summary

The depth bands feature replaces the simple "1% depth" price impact model with a 30-band system that provides granular control over price impact curves. This enhancement allows for more realistic market depth modeling.

### Added

#### New Features

* 30 configurable bands (0-29) representing different liquidity depths
* Piecewise calculation using trapezoidal rule for smooth price impact curves
* Linear extrapolation beyond 100% depth for very large trades
* Separate depth configurations for longs (above) and shorts (below)
* Efficient storage packing: all band data in 2 slots per direction
* Non-decreasing validation for band liquidity/offset values

#### New Data Structures

* `IPriceImpact.PairDepthBands` - Stores depth band liquidity configuration for each pair (4 slots: above/below × slot1/slot2)
* `IPriceImpact.DepthBandsMapping` - Global mapping of band indices to band percentage offsets from mid price (2 slots)
* `IPriceImpact.DepthBandParameters` - Working struct for depth band calculations

#### New Functions

* `initializeDepthBandsMapping(uint256 slot1, uint256 slot2)` - Initialize global bands offset mapping (reinitializer(25))
* `setPairDepthBands(uint256[] indices, PairDepthBands[] depthBands)` - Set depth bands liquidity for multiple pairs
* `setDepthBandsMapping(uint256 slot1, uint256 slot2)` - Configure global bands offset values
* `getPairDepthBands(uint256 pairIndex)` - Get single pair's encoded depth bands
* `getPairDepthBands(uint256[] indices)` - Get multiple pairs' encoded depth bands (array version)
* `getPairDepthBandsDecoded(uint256 pairIndex)` - Get single pair's decoded depth bands
* `getPairDepthBandsDecoded(uint256[] indices)` - Get multiple pairs' decoded depth bands (array version)
* `getDepthBandsMapping()` - Get global bands encoded mapping
* `getDepthBandsMappingDecoded()` - Get global bands decoded mapping

#### New Internal Functions

* `_getDepthBandsPriceImpactP()` - New price impact getter using depth bands
* `_getTotalDepthUsd()` - Extract total depth usd from encoded slot
* `_getBandValue()` - Extract band value from encoded slots (returns ppm for mappings, bps for depths)
* `_calculateDepthBandsPriceImpact()` - Core calculation using trapezoidal rule for average fill price

#### New Constants

* `DEPTH_BANDS_COUNT = 30` - Total number of depth bands
* `DEPTH_BANDS_PER_SLOT1 = 14` - Number of bands stored in slot1
* `HUNDRED_P_BPS = 1e4` - 100% in bps

### Changed

#### Libraries

* `PriceImpactUtils` is now external and has been adjusted for the new bands feature

#### Modified Functions

* `getTradeCumulVolPriceImpactP()` - Now forwards to `_getDepthBandsPriceImpactP` implementation using depth bands

#### Storage Updates

* `IPriceImpact.PriceImpactStorage` struct updated:
  * Added `mapping(uint256 => PairDepthBands) pairDepthBands`
  * Added `DepthBandsMapping depthBandsMapping`
  * Reduced `__gap` array to \[36] to accommodate new storage

### Deprecated

#### Storage

* `pairDepths` - Replaced by `pairDepthBands`

### Removed

#### Functions

* `setPairDepths()` - Replaced by `setPairDepthBands()`
* `getPairDepth()` - Replaced by `getPairDepthBands()`
* `getPairDepths()` - Replaced by array version of `getPairDepthBands()`

### Technical Details

#### Band Structure

**PairDepthBands** (per-pair liquidity configuration):

* Defines the actual liquidity distribution for each trading pair
* 30 bands representing cumulative percentages of total depth (0-100%)
* Each band liquidity percentage stored as basis points (bps), e.g., 2500 = 25% of total depth
* Separate configurations for above/below market price
* Storage encoding per direction:
  * Slot1: totalDepthUsd (32 bits) + bands 0-13 (16 bits each)
  * Slot2: bands 14-29 (16 bits each)

**DepthBandsMapping** (global offset configuration):

* Defines the cumulative offset from mid price at each band boundary
* Values stored as parts per million (ppm), e.g., 130 = 0.013% offset from mid price
* Storage encoding:
  * Slot1: bands 0-13 offsets (16 bits each, first 32 bits unused)
  * Slot2: bands 14-29 offsets (16 bits each)

#### Calculation Method

1. Iterate through bands until trade size is consumed
2. Use trapezoidal rule for average impact within each band
3. Weight each band's contribution by depth consumed
4. Support linear extrapolation beyond 100% for large trades

#### Variable Naming Conventions

* Variables ending in `Usd` represent USD-denominated values (1e18)
* Variables ending in `Ppm` represent parts per million (1e6) => percentage with 4 decimals
* Variables ending in `Bps` represent basis points (1e4) => percentage with 2 decimals
* `priceImpactP` represents price impact percentage in 1e10 precision

#### Migration Path

1. Initialize global depth bands mapping using `initializeDepthBandsMapping()`
2. Migrate existing pairs from old depth model to depth bands
3. New pairs should use `setPairDepthBands()` directly
4. Between deployment and setting bands, dynamic price impact will be 0
5. Monitor and adjust band configurations as needed

### Key Specifications

#### Backwards Compatibility

* **Fully backwards compatible**: The new depth bands system produces identical results to the previous linear formula when configured with linear bands and the same depth values

#### Validation Requirements

* **Pair depth bands**: Must include the value 100% (10,000 bps) as one of the band values and it must be the maximum value
* **Pair depth bands**: Must be non-decreasing across bands since they are cumulative (each band value ≥ previous band value)
* **Global depth offsets**: Must be non-decreasing across bands since they are cumulative (each offset ≥ previous offset)

#### Trade Splitting Protection

* **Cumulative volume price impact**: Has 2x weight in the calculation to ensure trade splitting remains unprofitable
* This design choice prevents traders from gaming the system by splitting large trades into smaller ones

### Gas Optimization

* Efficient storage packing reduces reads to 2 slots per direction + 2 slots for global offsets => 4 slots total
* Early exit from loop when trade size has been consumed


# v10.1 Update

### Changelog

* All parameter updates (borrowing/funding) which require the current pair price are no longer done using the request/callback pattern but using signed prices from the oracles directly, in a single transaction
* Triggering orders (SL/TP/LIQ/LIMIT\_OPEN/STOP\_OPEN) is now also possible using signed pair prices in a single transaction (previous request/callback pattern still exists as backup)
* This both saves gas (5 less transactions) and decreases execution time
* Signed pair prices are validated, stored temporarily in storage, and cleaned up at the end of the transaction so the storage gas costs are refunded
* Refactored aggregator answer validation (OHLC values) and median/outliers filtering into separate helpers, re-used for signed prices validation (exact same logic as in `fulfill`)
* Updated `SL_LIQ_BUFFER_P` to `5%`, from `10%`
* Refactored `_limitSlDistance` to account for open and close fees, now min is `liqThreshold - 2 * totalPositionSizeP * leverage - SL_LIQ_BUFFER_P`.
* Updated `withinExposureLimits` to allow skew improvements even when skew is above max, uses new `withinSkewLimits` helper.


# v10 Update

### Changelog

* TradingCallbacksUtils and TradingInteractionsUtils are now external
* New external libraries: FundingFeesUtils (new holding fees logic), TradeManagementCallbacks (pnl withdrawal, negative pnl/holding fees realization), TradingStorageGetters (previously ArrayGetters)
* New GOV\_EMERGENCY\_TIMELOCK role (setRoles, diamondCut) => 10-hour emergency timelock so we can do emergency fixes
* Post-v10 OI stored separately from pre-v10 (collateral + token OIs)
  * Old borrowing fees and new borrowing fees are charged on all OI (pre-v10 and post-v10)
  * New funding fees are only charged on post-v10 OI
  * Counter trade skew calculation uses post-v10 OI only
  * Skew price impact calculation uses post-v10 OI only
  * Max skew check uses post-v10 OI only
  * Pair max OI check uses all OI (pre-v10 and post-v10)
  * Pair OI updates now done from \_updateOi instead of handleTradeBorrowingCallback (calls pre-v10 setter for pre-v10 trades and post-v10 setter for post-v10 trades), group OI still updated from handleTradeBorrowingCallback
* New funding fees facet: funding fees and new borrowing fees
  * All new funding/borrowing fees data and settings are stored per pair and collateral
  * Everything is backwards compatible: a pair can have old borrowing fees, new funding fees, and new borrowing fees (any combination)
  * Funding rate per second's velocity per year = skew coefficient per year \* net exposure in tokens, absolute value capped at max velocity setting, only > 0 when net exposure usd > theta threshold usd
  * Funding rate = last rate + seconds elapsed \* velocity per year / seconds in a year, absolute value capped at max rate setting (hard cap at 10,000% APR)
  * Acc funding fees delta = avg funding rate per second % since last update \* seconds elapsed \* current pair price (incremented at every trade, whenever OI or a funding parameter changes), trade funding fee = (current acc funding fee - initial acc funding fee) \* position size collateral / entry price / 100 = sum(avg funding rate per second % \* seconds elapsed \* current pair price) since trade opened \* position size collateral / entry price / 100 = sum(funding rate % \* current pair price \* position size token / 100) since trade opened = sum(funding rate % \* position size collateral dynamic / 100) since trade opened
  * Can enable/disable funding fees and enable/disable APR multiplier logic on each pair/collateral (resumes from last rate when we re-enable)
  * APR multipliers use the OI in token amounts (not collateral amounts) to calculate the ratio of longs/shorts (capped at 100x to prevent overflows), otherwise it wouldn't be balanced since the total funding fee on one side is acc fee delta / 100 \* total OI token
  * New borrowing rate (same on each side) can be defined on each pair/collateral (hard cap at 1,000% APR)
  * Funding fees and borrowing fees are charged on the dynamic position size in collateral tokens (scaled by current price / entry price) to mimic CEXes behavior
* New max OI skew in collateral tokens per pair/collateral (uses net skew in tokens \* current pair price => dynamic OI collateral skew)
* Pair max OI check now uses dynamic OIs in collateral tokens (= pre-v10 OI collateral + post-v10 OI token \* current pair price)
* Old borrowing fees refactor:
  * Old borrowing fees calculations now require current pair price (rate is calculated using dynamic OIs collateral)
  * Still charged on initial position size collateral for now, would require factoring acc fee
  * Borrowing pair params setter was refactored to use callback pattern
  * Borrowing groups however still use initial OIs for borrowing rate calculation and max OI check
* New param updates callback mechanism:
  * Specific job id (market)
  * Uses address(1) to store pending order in order to have a global id
  * Pending param updates are stored in funding fees facet
  * New parameter value has to fit into uint224 (pending param update = collateral index, pair index, update type, and new value packed into 1 slot)
* Before any trading action that impacts size of an open trade (partial add/close, full close), pending holding fees are realized (reset to 0, stored as realized pnl, if positive sent to vault without burn)
* Realized pnl of each trade is split between realized pnl (only impacts trade value) and realized trading fees (impacts both trade value and available collateral in diamond)
* 3 new other vars impact availble collateral in diamond:
  * manuallyRealizedNegativePnlCollateral: equal to the negative pnl we sent to the vault to balance potential closed pnl imbalances (eg. huge negative open pnl but all trades closing have positive pnl)
  * alreadyTransferredNegativePnlCollateral: equal to the total partial close negative pnl sent to the vault (for leverage delta > 0)
  * virtualAvailableCollateralInDiamond: when withdrawing collateral with positive pnl it's possible there isn't enough collateral in diamond, however available collateral in diamond must be >= 0 after withdrawing collateral (we prioritize capping manuallyRealizedNegativePnlCollateral at new collateral amount and if not enough we compensate through this variable); otherwise if negative then when user deposits collateral it doesn't increase available in diamond and can deposit/withdraw in loop to drain the vault
* The function to realize trading fees on an open trade also checks if the trade can be liquidated after charging the fee, and if so liquidates it in order to avoid someone spamming trade actions potentially before we have time to liquidate him with trigger bots resulting in more fees than his trade can afford
* Partial close refactor:
  * The value sent to the trader is now the partial collateral + net pnl - closing fee, exactly equivalent to the full close formula (later we could refactor to remove full close code and only use partial close code and just close trade when partial close size = trade size)
  * For collateral delta > 0 we just scale the full trade down (realized pnl and available collateral in diamond) so new trade value + sent to trader = prev trade value, the trading fee is taken from what we send to the trader (collateral sent to trader < 0 not allowed), and the available collateral in diamond used is the proportional available collateral in diamond based on the position size delta
  * For leverage delta > 0 we realize the partial unrealized raw pnl (since position size is lower if we didn't do this it would lower the trade's pnl) minus what we sent to the trader so new trade value + sent to trader (when positive, otherwise gets sent to vault) = prev trade value, we charge the trading fee on the open trade (transfers fee from vault if available in diamond = 0), the available collateral in diamond is always zero (removed old traderDebt logic which used to realize partial negative pnl by reducing trade collateral), and if net pnl is negative we send the partial negative pnl (pending + realized) minus the manually realized pnl and already transferred negative pnl (already sent to vault in a previous partial close) to the vault, capped at total trade available collateral in diamond, we don't just send the partial net pnl to the vault because for example realized trading fees are not in the diamond so it wouldn't make sense
* UI realized pnl data contains a useful data breakdown to display for the website backend/frontend, since the realized pnl value used on-chain to calculate the trade value is not really what the user expects to see as realized pnl (eg. when withdrawing collateral we realize negative pnl even if this action corresponds to realizing positive pnl because we have to impact the trade's value negatively to prevent withdrawing the same pnl, or eg. the trade's realized pnl gets scaled down on partial closes so it doesn't correspond to the total anymore)
* New counter trade mechanism:
  * Can only be below a defined leverage to qualify (check on trade opening, partial adds, leverage increases), set per pair
  * Has to improve skew (any size that worsens the skew is returned to the user as collateral or leverage delta reduced for partial adds when collateral delta = 0)
  * Uses dynamic OI collateral skew (skew token \* current pair price)
  * Benefit from trading fees discount, set per pair
  * Both trades and limit/stop orders can be counter trades (once executed they turn into counter-trade trades)
* New skew price impact:
  * Calculated using (existing skew token + trade size token / 2) / skew depth token (existing skew and trade size being signed integers)
  * Trade size token is calculated using position size collateral / price after fixed spread and cumulative volume price impact on partial add and full open, and using position size collateral delta \* trade position size token / trade position size collateral on partial close and full close (the same value is used to update pair token OIs)
  * Not included in max negative pnl on open check since it's neutral for pnl when opening and closing (otherwise couldn't trade when skew is too high)
  * Calculated using post-v10 skew only, pre-v10 trades don't pay any skew price impact on close
  * Specific skew depth stored per pair and collateral (same on both sides)
* Price impact refactor: now fixed spread, cumulative vol price impact, and skew price impact percentages are first summed and then applied to the oracle price instead of applying them one on top of another
* Pre-v10 trades can no longer partial add otherwise it would be a way to bypass the new funding fees and skew price impact
* Traders can now withdraw net pnl from their trades without impacting their position size
* We can now realize the pending holding fees of an open trade (eg. to solve imbalance if more trades closed with earned funding fees than paid funding fees temporarily)
* We can now realize the negative pnl of an open trade (eg. to solve imbalance if more trades closed with positive pnl than negative pnl temporarily) => includes closing fixed spread and closing skew price impact, not closing cumulative volume price impact to avoid over-estimating negative PnL
* Significant gas optimization: getTrade and getTradeInfo turned internal and use the library directly to avoid overhead from calling diamond proxy
* GToken vaults receiveAssets function now supports a \_burn argument so we can send funding fees to the vault without burning them (since they are neutral, an equivalent amount of funding fees will be taken out of vault later)
* All trading fees (opening, partial add/close etc.) / holding fees / partial negative pnl (leverage delta > 0) no longer impact the trade's collateral / position size when charged, they are stored as realized trading fees and just impact the trade's value / available collateral in diamond, so when a user opens a trade with 100 DAI at 20x it now opens exactly with 2,000 DAI size
* Leverage validation refactor:
  * Partial add / increase leverage: Instead of validating the adjusted initial leverage to be below the max leverage, we now do this check on the new effective leverage (which increases when pnl is negative and decreases when pnl is positive)
  * Partial add/close and increase/decrease leverage: We only validate the adjusted initial leverage to be below 0.1x and uint24.max (unlikely to be hit)
  * Partial close / decrease leverage: removed minimum leverage checks apart from the adjusted initial leverage one (none on effective leverage), only one left is on full open (can easily be bypassed by partially closing or decreasing leverage after trade is opened but doesn't matter)
* Partial close / Increase leverage: simplified minimum new collateral amount in requestion validation, now just has to be > min fee
* Partial add refactor:
  * Removed new pos size > old pos size check in request validation since fees no longer impact the position size (still checks in callback because can happen due to rounding down of leverage when collateral delta > 0 but very unlikely)
  * Re-calculates the new position size after calculating new collateral / leverage (can be different than old pos + pos size delta due to leverage rounding)
  * Major bugfix: calculates existingPnlCollateral for new open price calculation using price after impact (before used raw oracle price)
  * New open price now rounded up for longs and down for shorts to avoid generating positive pnl due to rounding
  * Simplified oldPosSizePlusPnlCollateral calculation using int
* Net trade value and liquidation price calculations now take into account the pending new funding/borrowing fees too as well as the realized pnl
* Oracle changes:
  * Now expected to no longer reply anything when the market is closed (because now we need the current pair price to realize trading fees on a trade to check if it can be liquidated and if we don't have it and just allow requests there can be a spam vector)
  * Requests can no longer be responded to 1 hour after they are initiated to prevent from keeping them pending
  * Expected to pass the current pair price too for lookback orders now since we need it to calculate pending holding fees
* Closing fees are now always charged on full close, before it used to check if collateral was higher than the closing fee but it doesn't make sense anymore since a trade's collateral can't go below the min fee (check in partial close and increase leverage), and if there isn't enough available collateral in diamond it becomes negative so it's sent from vault to diamond and then distributed
* Leverage updates and partial closes now both check the existing and new liq price
* Leverage updates no longer result in \_updateOi calls even if there's a tiny position size difference due to rounding, doesn't matter
* Only amount that gets burned anymore is the negative pnl on full close which is still available in diamond as well as partial close negative pnl (not holding fees, trading fees, or manually realized negative pnl)
* Added liquidation check in \_openTradePrep to prevent executing a limit/stop order with lookbacks which would be immediately liquidated due to current pair price having moved too much against trade
* Liquidation price calc function now accepts additional fee as input to simulate liq price after charging a fee / realizing pnl
* Old price aggregator orderAnswers mapping deprecated in favor of new one that can store the current pair price (prices of OrderAnswer are now uint56 instead of uint64, max price is 7,205,759), any pending order from before v10 that wasn't fulfilled will have to be canceled after timeout and re-initiated
* AggregatorAnswer no longer contains spreadP, now fetched from within getTradeOpeningPriceImpact and getTradeClosingPriceImpact
* New ContractsVersion value of V10 to differentiate from trades opened before v10 (for trades opened before v10: no funding fee, no skew price impact, separate OI mapping, cannot partial add)
* Trade struct now contains two additional properties: isCounterTrade and positionSizeToken (still fits into 3 slots)
* Removed isWithinExposureLimit check in partial add and open trade request validation because it now requires the current pair price (for dynamic max skew calculation), check is still in callback
* getTradeFeesCollateral / processFees now accept fee as input so calling function has to refresh fee tier and calculate the fee before calling, and the current trade fee tier points are only counted towards the next trade (before, a trade's fee tier points were credited before this same trade was executed, potentially making it reach the next fee tier for this same trade, impacting its fee)
* No longer refresh fee tier in triggerOrder when byPassesLinkCost = false because we use a fixed link cost


# v9.2.1 Update

## Summary

* 50% of the spread and price impact is now charged on trade opening and closing instead of 100% on trade opening
* Existing trades don't pay any spread or impact on close (since they already paid in full on open), and they keep paying 100% spread when partial adding
* Spread and price impact on close use the reverse direction as opening spread (makes price lower for longs and higher for shorts)
* Price impact on close uses the opposite side depth and opposite side price impact OI (= cumulative vol now)
* Price impact OI windows now use new cumulative volume logic (much shorter windows duration possible because more accurate, opening a long / closing a short uses/adds to long windows, opening a short / closing a long uses/adds to short windows, new cumulative factor which will be set to 1 to start with but can be used to adjust weight of price impact OI in price impact formula), we never remove any OI from windows anymore (logic much simpler, no longer need to move trade OI to current window for partials)
* Closing price impact higher for short-term trades (depending on protection factor blocks duration and protection factor multiplier per pair), only when net PnL is positive
* Liquidation price now takes into account the closing spread (not the price impact) for trades opened after v9.2 and uses new logic for the liquidation pnl % threshold (closer pnl % threshold as leverage increases, more aggressive for higher leverages similarly to MMR)
* Existing trades aren't affected by the new liquidation threshold logic, liquidation parameters for trades are stored on opening so they can't change for an open trade even when a group's liquidation parameters are updated, however a trade's liquidation params are refreshed to current value when position size is increased using partials
* New stop loss max distance is `liqPnlThresholdP - 10%` (eg. -70% PnL when trade liq pnl % threshold is -80%)
* Added max slippage on close (market close, partial close, tp/sl) mechanism: by default 1% for all opened trades, can be adjusted after trade is open
* Extracted cancel reason logic for limit/stop/tp/sl/liq callbacks into getters, will be used by EA-lookbacks to check ability to execute at past chain state
* LIQ triggers no longer turned into SL triggers when SL is closer otherwise user could set very low max closing slippage and would never be able to be liquidated if price went past his SL and LIQ price, trigger bots will prioritize SL over LIQ when possible

## Full Changelog

### core/facets/GNSPairsStorage.sol (update)

* Added `initializeGroupLiquidationParams`, `setGroupLiquidationParams`, `getGroupLiquidationParams`, and `getPairLiquidationParams`

### core/facets/GNSPriceAggregator.sol (update)

* `getPrice` now accepts `_tradeId` instead of `_trader`

### core/facets/GNSPriceImpact.sol (update)

* Added `initializePairFactors`, `setProtectionCloseFactors`, `setProtectionCloseFactorBlocks`, `setCumulativeFactors`, `getPairFactors`
* Removed `removePriceImpactOpenInterest`, `getTradeLastWindowOiUsd`, `getTradePriceImpactInfo`
* `addPriceImpactOpenInterest` now accepts `_open` argument
* `getTradePriceImpact` now accepts `_isPnlPositive`, `_open`, `_lastPosIncreaseBlock`, and `_contractsVersion` arguments

### core/facets/GNSTradingCallbacks.sol (update)

* Added `validateTriggerOpenOrderCallback` and `validateTriggerCloseOrderCallback` getters

### core/facets/GNSTradingInteractions.sol (update)

* New `updateMaxClosingSlippageP` function
* `closeTradeMarket` and `decreasePositionSize` now accept `_expectedPrice` argument (used for max slippage check in callbacks)

### core/facets/GNSTradingStorage.sol (update)

* New `updateTradeMaxClosingSlippageP` function
* `updateTradePosition` now accepts `_isPartialIncrease` argument
* Added `getTradeLiquidationParams`, `getTradesLiquidationParams`, `getAllTradesLiquidationParams`, and `getCurrentContractsVersion`

### interfaces/IGeneralErrors.sol (update)

* Added `WrongOrderType()` error

### interfaces/libraries/IPairsStorageUtils.sol (update)

* Added new function definitions
* Added `GroupLiquidationParamsUpdated` event
* Added `MaxLiqSpreadPTooHigh`, `WrongLiqParamsThresholds`, `WrongLiqParamsLeverages`, `StartLiqThresholdTooHigh`, `EndLiqThresholdTooLow`, `StartLeverageTooLow`, `EndLeverageTooHigh`

### interfaces/libraries/IPriceAggregatorUtils.sol (update)

* Adjusted `getPrice` function definition
* Updated `PriceRequested` event: now emits `tradeId` instead of `trader`

### interfaces/libraries/IPriceImpactUtils.sol (update)

* Added new function definitions
* Removed deprecated function definitions
* Adjusted `addPriceImpactOpenInterest` and `getTradePriceImpact` functions definitions
* Added `ProtectionCloseFactorUpdated`, `ProtectionCloseFactorBlocksUpdated`, and `CumulativeFactorUpdated` events
* Removed `isPartial` from `PriceImpactOpenInterestAdded` event
* Removed `PriceImpactOpenInterestRemoved` event

### interfaces/libraries/ITradingCallbacksUtils.sol (update)

* Added `validateTriggerOpenOrderCallback` and `validateTriggerCloseOrderCallback` functions definitions

### interfaces/libraries/ITradingCommonUtils.sol (update)

* Added `TradePriceImpactInput` struct to avoid stack too deep in `getTradeClosingPriceImpact`

### interfaces/libraries/ITradingInteractionsUtils.sol (update)

* Added `updateMaxClosingSlippageP` function definition
* Adjusted `closeTradeMarket` and `decreasePositionSize` functions definitions
* Removed `WrongOrderType()` error

### interfaces/libraries/ITradingStorageUtils.sol (update)

* Added new function definitions
* Adjusted `updateTradePosition` function definition
* `TradeStored` event now also emits the trade liquidation params
* `TradePositionUpdated` now emits `isPartialIncrease`
* New `TradeMaxClosingSlippagePUpdated` event

### interfaces/libraries/IUpdatePositionSizeUtils.sol (update)

* Added `long` and `collateralPriceUsd` properties to `PositionSizeIncreaseExecuted` and `PositionSizeDecreaseExecuted` events

### interfaces/types/IBorrowingFees.sol (update)

* `LiqPriceInput` struct has new `liquidationParams` property

### interfaces/types/IPairsStorage.sol (update)

* Added `groupLiquidationParams` mapping and corresponding `GroupLiquidationParams` struct
* `__gap` length decreased from 41 to 40

### interfaces/types/IPriceImpact.sol (update)

* Added `pairFactors` mapping
* `__gap` length decreased from 46 to 45
* Added `_open` property to `OiWindowUpdate` struct
* New `PairFactors` struct

### interfaces/types/ITradingStorage.sol (update)

* Added `tradeLiquidationParams` mapping
* `__gap` length decreased from 39 to 38
* New `ContractsVersion` enum
* `TradeInfo` struct now has `contractsVersion` and `lastPosIncreaseBlock` properties, and `__placeholder` was reduced from `uint48` to `uint8`

### interfaces/types/IUpdatePositionSize.sol (update)

* Added `expectedPrice` property to `DecreasePositionSizeInput` struct
* Added `priceAfterImpact` property to `DecreasePositionSizeValues` struct

### libraries/ArrayGetters.sol (update)

* Added `getTradesLiquidationParams` and `getAllTradesLiquidationParams` getters

### libraries/BorrowingFeesUtils.sol (update)

* `getTradeLiquidationPrice`: calculate `closingFeesCollateral` using new `TradingCommonUtils.getTotalClosingFeesCollateral` helper, pass input liquidation params, trade contracts version, and pair spread % to `_getTradeLiquidationPrice`
* `_getTradeLiquidationPrice`: new `_liquidationParams`, `_contractsVersion`, and `_pairSpreadP` arguments, `_collateralPrecisionDelta` is now uint256 (saves one var to avoid stack too deep), calculate `liqPnlThresholdP` using new `TradingCommonUtils.getLiqPnlThresholdP` helper, in `collateralLiqNegativePnlInt` calculation divide by `1e10` because of new liq threshold precision, if trade opened after v9.2 make liquidation price distance lower by closing spread (= 1/2 pair spread %, capped at `maxLiqSpreadP`)

### libraries/ConstantsUtils.sol (update)

* Replaced `MAX_SL_P` by `SL_LIQ_BUFFER_P=10%`, renamed `LIQ_THRESHOLD_P` to `LEGACY_LIQ_THRESHOLD_P`, added `MIN_LIQ_THRESHOLD_P=50%`/`MAX_LIQ_SPREAD_P=0.05%`/`DEFAULT_MAX_CLOSING_SLIPPAGE_P=1%`

### libraries/PairsStorageUtils.sol (update)

* New `initializeGroupLiquidationParams` function: initializes group liquidation params for all existing groups
* New `setGroupLiquidationParams` function: used to update a group's liquidation params (only affects trades opened after the change)
* New `getGroupLiquidationParams` and `getPairLiquidationParams` getters

### libraries/PriceAggregatorUtils.sol (update)

* `getPrice`: now accepts `_tradeId` argument instead of `_trader`, passes `trader`/`index`/`orderType` data to `linkRequest`

### libraries/PriceImpactUtils.sol (update)

* `MAX_WINDOWS_DURATION` lowered from 30 days to 10 minutes, `MIN_WINDOWS_DURATION` lowered from 10 minutes to 1 minute
* New `initializePairFactors` function that initializes pairs factors
* New `setProtectionCloseFactors` to set the protection close factors for a set of pairs
* New `setProtectionCloseFactorBlocks` to set the protection close factor duration in blocks for a set of pairs
* New `setCumulativeFactors` to set the cumulative factors for a set of pairs
* `addPriceImpactOpenInterest`: Removed partials logic that moved previous trade OI to current window if not expired, changed logic to decide if adds to long or short part of window (opening a long / closing a short adds to long window, opening a short / closing a long adds to short window), removed `lastWindowOiUsd` update (deprecated)
* Removed `removePriceImpactOpenInterest` and `getTradeLastWindowOiUsd`
* `getTradePriceImpact`: new `_isPnlPositive`/`_open`/`_lastPosIncreaseBlock`/`_contractsVersion` arguments, now loads `pairFactors` for pair, uses opposite side depth when `_open = false`, uses opposite side price impact OI when `_open = false`, passes `_open`, `protectionCloseFactor` (only when `_isPnlPositive` is true, `_open` is false, `protectionCloseFactor` isn't zero, and protection close factor didn't expire, otherwise passes `1e10`), `cumulativeFactor` (when not zero, otherwise passes `1e10`), and `_contractsVersion` to `_getTradePriceImpact`
* Removed `getTradePriceImpactInfo` (deprecated)
* New `getPairFactors` getter
* `_getTradePriceImpact`: new `_open`, `_protectionCloseFactor`, `_cumulativeFactor`, `_contractsVersion` arguments, returns early 0 price impact if trade opened before v9.2 and `_open = false` (no closing price impact for trades opened before v9.2 since they paid it fully on open), multiplies `_startOpenInterestUsd` by `_cumulativeFactor`, multiplies by `_protectionCloseFactor` instead of `1e10` in `priceImpactP` calculation and divides result by 2 if trade opened after v9.2 (charge half price impact if trade opened after v9.2 since they paid half on open already, for trades opened before v9.2 charges full opening price impact), sets `_long` to `!_long` if `_open` is false to invert the price impact direction on close

### libraries/TradingCallbacksUtils.sol (update)

* `closeTradeMarketCallback`: use new `_getTradeInfo` getter, Add `TradingCommonUtils.getTradeClosingPriceImpact` call, added max slippage cancel reason check (uses default max slippage % if `tradeInfo.maxSlippageP` not set), use `priceAfterImpact` (= market price + closing spread and price impact) instead of `_a.price` to calculate `v.profitP`, emit `priceAfterImpact` and `priceImpactP` in event
* `executeTriggerOpenOrderCallback`: moved all cancel reason and spread/price impact logic to `validateTriggerOpenOrderCallback`
* `executeTriggerCloseOrderCallback`: moved all cancel reason and spread/price impact logic to `validateTriggerCloseOrderCallback`, emit `priceImpactP` in `LimitExecuted` event
* `validateTriggerOpenOrderCallback`: new getter that contains the extracted cancel reason logic of `executeTriggerOpenOrderCallback`
* `validateTriggerCloseOrderCallback`: new getter that contains the extracted cancel reason logic of `executeTriggerCloseOrderCallback`, for SLs and TPs (not liquidations) set `v.executionPrice` to `TradingCommonUtils.getTradeClosingPriceImpact` result to take into account closing spread and impact, added max slippage cancel reason check for everything but liquidations (uses default max slippage % if `tradeInfo.maxSlippageP` not set)
* `_openTradePrep`: no logic change, just use new `TradingCommonUtils.getTradeOpeningPriceImpact` helper to calculate opening price impact
* New `_getTradeInfo` getter

### libraries/TradingCommonUtils.sol (update)

* `getMarketExecutionPrice`: new `_open`/`_contractsVersion` arguments, returns early with 0 spread if `_open = false` and `_contractsVersion = before v9.2`, divides spread by 2 if `_contractsVersion >= v9.2`, inverts spread direction when `_open` = false
* `getTradeValuePure`: combined `_borrowingFeeCollateral` and `_closingFeeCollateral` into `_feesCollateral` to avoid stack too deep, added `_liqPnlThresholdP` argument, `collateralLiqThreshold` is now `uint256` and uses `_liqPnlThresholdP` instead of `ConstantsUtils.LIQ_THRESHOLD_P` and is adjusted for `1e10` precision, added `int256` conversion for `collateralLiqThreshold` in return statement
* `getLiqPnlThresholdP`: new pure function that returns the corresponding liquidation PnL threshold percentage to use depending on a trade's liquidation params and leverage; uses new logic (linearly decreasing liq pnl threshold as leverage increases, capped between two values)
* `getTradeLiquidationPrice`: pass the stored trade's liquidation params
* `getTradeValueCollateral`: pass `borrowingFeesCollateral + _closingFeesCollateral` to `getTradeValuePure` instead of passing them separately, and also pass `getTradeLiqPnlThresholdP(_trade)`
* `getTradeOpeningPriceImpact`: New view helper to calculate the price impact % and price after spread + price impact for trade openings / partial adds
* `getTradeClosingPriceImpact`: New view helper that returns the closing price impact %, price after closing spread and impact, and net trade value used to determine whether net pnl is positive or not; returns early 0% price impact for trades opened before v9.2, otherwise calculates net trade value (taking into account pnl, spread, price impact, closing fees, and borrowing fees) without protection factor and compares it to the initial trade collateral to determine the `_isPnlPositive` value passed to `getTradePriceImpact` which determines the final returned `priceImpactP` and `priceAfterImpact` values
* `getTradeLiqPnlThresholdP`: new getter that returns the value of `getLiqPnlThresholdP` by passing the trade's stored liquidation params and its leverage
* `getTotalClosingFeesCollateral`: new getter that returns a trade's closing fee based on its `_collateralIndex`/`_pairIndex`/`_positionSizeCollateral`, used in `BorrowingFeesUtils.getTradeLiquidationPrice`/`TradingCommonUtils.getTradeClosingPriceImpact`/`DecreasePositionSizeUtils.validateRequest`
* Renamed `addOiCollateral` to `updateOi`, now accepts `_open` argument and passes it to `handleTradeBorrowingCallback` and `addPriceImpactOpenInterest`
* Renamed `addTradeOiCollateral` to `updateOiTrade`, now accepts `_open` argument and passes it to `updateOi`
* Removed `removeOiCollateral` and `removeTradeOiCollateral`
* `handleOiDelta` now uses `updateOi`, passes `_open = true` when `_newPositionSizeCollateral > existingPositionSizeCollateral` and `_open = false` when `_newPositionSizeCollateral < existingPositionSizeCollateral`

### libraries/TradingInteractionsUtils.sol (update)

* New `updateMaxClosingSlippageP` function that simply calls `GNSTradingStorage.updateTradeMaxClosingSlippageP`
* `closeTradeMarket`: now accepts `_expectedPrice`, reverts if `_expectedPrice` is 0, sets `pendingOrder.trade.openPrice` to `_expectedPrice`, passes trade id to `getPrice`
* `decreasePositionSize`: now accepts `_expectedPrice`, passes it to `requestDecreasePositionSize`
* `triggerOrder`: no longer turn LIQ orders into SL orders when SL is closer, uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `priceImpactP`
* `_openTrade`: uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `priceImpactP`, passes trade id to `getPrice`
* `_getPriceTriggerOrder`: passes trade id to `getPrice`

### libraries/TradingStorageUtils.sol (update)

* `storeTrade`: Fetches the corresponding pair's liquidation params and stores them into the new `tradeLiquidationParams` mapping, limits the trade SL distance using the new `_limitTradeSlDistance` helper, sets `_tradeInfo.contractsVersion` to the current version using `getCurrentContractsVersion()`, sets `_tradeInfo.lastPosIncreaseBlock` to current block, no longer sets `_tradeInfo.lastOiUpdateTs = 0` because corresponding logic was deprecated, calls `updateOiTrade` with `_open = true` instead of `addTradeOiCollateral`, emits the trade's liquidation params
* New `updateTradeMaxClosingSlippageP` setter
* `updateTradePosition`/`updateOpenOrderDetails`/`updateTradeSl`: limit the trade's SL distance using the new `_limitTradeSlDistance` helper instead of `_limitSlDistance`
* `updateTradePosition`: new `_isPartialIncrease` argument, sets the trade's stored liquidation params to the current pair liquidation params when `_isPartialIncrease = true` and sets `i.lastPosIncreaseBlock` to current block, emits `_isPartialIncrease` in `TradePositionUpdated` event
* `closeTrade`: calls `updateOiTrade` with `_open = false` instead of `removeTradeOiCollateral`
* `getTradeLiquidationParams`: new getter to return the new `tradeLiquidationParams` mapping values
* `getCurrentContractsVersion`: new getter to return the current contracts version (will need to be updated at each significant update)
* `_limitSlDistance`: accepts new `_liqPnlThresholdP` argument, calculates `minSlP` as `_liqPnlThresholdP - ConstantsUtils.SL_LIQ_BUFFER_P`, uses calculated `minSlP` instead of `ConstantsUtils.MAX_SL_P`, adjustments done for `1e10` precision of `minSlP`
* `_limitTradeSlDistance`: new view wrapper accepting `_trade` and `_newSl` arguments; returns a trade's capped SL distance based on its open price, leverage, new stop loss value, whether it's a long or a short, and based on its liquidation pnl % threshold fetched using `TradingCommonUtils.getTradeLiqPnlThresholdP(_trade)`

### libraries/updateLeverage/UpdateLeverageLifecycles.sol (update)

* `_initiateRequest`: small adjustment to avoid stack too deep, now passes trade id to `getPrice`
* `_prepareCallbackValues`: pass stored trade liquidation params in `values.liqPrice` calculation
* `_handleCallback`: pass `_isPartialIncrease = false` to `updateTradePosition`

### libraries/updatePositionSize/DecreasePositionSizeUtils.sol (update)

* `validateRequest`: calculate `closingFeesCollateral` using new `TradingCommonUtils.getTotalClosingFeesCollateral` helper, revert if `input.expectedPrice` is 0
* `prepareCallbackValues`: added `values.priceAfterImpact` calculation using new `TradingCommonUtils.getTradeClosingPriceImpact` helper, `values.existingPnlCollateral` now uses `uint64(values.priceAfterImpact)` instead of `_answer.price`
* `validateCallback`: now accepts `_pendingOrder` (to fetch expected price), added max slippage calculations and corresponding cancel reason check (uses default max slippage % if `tradeInfo.maxSlippageP` not set)
* `updateTradeSuccess`: pass `_isPartialIncrease = false` to `updateTradePosition`

### libraries/updatePositionSize/IncreasePositionSizeUtils.sol (update)

* `prepareCallbackValues`: Uses `TradingCommonUtils.getTradeOpeningPriceImpact` to calculate `values.priceAfterImpact`, passes current pair liquidation params to `getTradeLiquidationPrice` for `values.newLiqPrice` calculation (already checks using new liquidation params since trade liquidation params will be refreshed on success callback)
* `updateTradeSuccess`: pass `_isPartialIncrease = true` to `updateTradePosition`

### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (update)

* `requestDecreasePositionSize`: passes `_input.expectedPrice` to `_initiateRequest`
* `_initiateRequest`: passes trade id to `getPrice`
* `executeIncreasePositionSizeMarket`/`executeDecreasePositionSizeMarket`: pass trade long and current collateral/usd price to event
* `executeDecreasePositionSizeMarket`: pass `_order` to `DecreasePositionSizeUtils.validateCallback`


# v9.1 Update

## Summary

* New features: GNS staking fees are all used to buy GNS, sends an adjustable % to treasury, burn, and GNS staking rewards and uses an adjustable price premium; new compound function in GNS staking
* Other changes: There is a 100 seconds cooldown to wait before one can unstake after staking GNS to prevent flashloans (vests must be 100 seconds long at least too now)

## Full Changelog

### core/GNSStaking.sol (update)

* New `UNSTAKING_COOLDOWN_SECONDS` constant (= 100 seconds)
* New `stakerInfos` mapping to store each user's lastDepositTs
* New `notInCooldown` modifier, used by `unstakeGns`, reverts if user deposited less than `UNSTAKING_COOLDOWN_SECONDS` ago
* `_harvestToken`, `_harvestFromUnlock`, `_harvestTokenFromUnlock`, `harvestToken`, `harvestTokenFromUnlock`, `harvestTokenAll` now all return the pending token rewards (needed for compound function)
* New `compoundGnsRewards` function: harvests pending regular rewards and vest rewards (accepts vests `_ids` as input) and stakes them in the same transaction
* `stakeGns`: now public (called by `compoundGnsRewards`) and stores current timestamp in `stakerInfos` mapping for caller
* `unstakeGns`: now uses `notInCooldown` modifier
* `createUnlockSchedule`: now checks vest duration >= `UNSTAKING_COOLDOWN_SECONDS` instead of accepting any non-zero value

### core/abstract/GNSDiamondStorage.sol (update)

* Added `otcStorage` private state var for new `GNSOtc` facet

### core/facets/GNSOtc.sol (new)

* New facet which handles the collateral -> GNS OTC buying process and transfer to treasury, burn, and GNS staking rewards (adjustable percentages)
* `initializeOtc`: infinite approval of GNS staking contract for GNS token and config initialization
* `updateOtcConfig`: update treasury address and percentages
* `addOtcCollateralBalance`: increases available collateral balance for OTC buying (used by `GNSTradingCallbacks` when distributing GNS staking fee)
* `sellGnsForCollateral`: executes OTC transaction; diamond receives GNS and sender receives collateral tokens, available collateral balance for OTC decreases accordingly
* `getOtcConfig`, `getOtcBalance`, `getOtcRate` getters

### interfaces/IGNSMultiCollatDiamond.sol (update)

* Now inherits `IOtcUtils`

### interfaces/IGNSStaking.sol (update)

* New `StakerInfo` struct (`lastDepositTs` and placeholder)

### interfaces/IGeneralErrors.sol (update)

* New `InsufficientBalance()` error

### interfaces/libraries/IOtcUtils.sol (new)

* Interface for new `GNSOtc` facet: contains all types, functions, events, and custom errors

### interfaces/types/IOtc.sol (new)

* Interface for new `GNSOtc` facet: contains all types
* `OtcStorage` struct: `collateralBalances` mapping, `otcConfig` struct
* `OtcConfig` struct: treasury address, percentages (treasury, GNS staking, burn), price premium

### interfaces/types/IPriceAggregator.sol (update)

* Fixed `__gap` array length, reduced from 41 to 39

### interfaces/types/ITypes.sol (update)

* Now inherits new facet types `IOtc`

### libraries/OtcUtils.sol (new)

* Internal library for new `GNSOtc` facet

### libraries/StorageUtils.sol (update)

* Added `GLOBAL_OTC_SLOT` constant for new `GNSOtc` facet

### libraries/TradingCommonUtils.sol (update)

* `convertCollateralToGns`, `transferCollateralTo`, and `_getMultiCollatDiamond` are now internal: allows not linking TradingCommonUtils to `GNSOtc` as internal functions are imported directly into the bytecode, should only make functions external when it becomes an issue for size
* New `transferGnsTo` and `transferGnsFrom` helpers to handle simple GNS transfers between users and the diamond
* `distributeGnsStakingFeeCollateral` now calls `_getMultiCollatDiamond().addOtcCollateralBalance` instead of `gnsStaking.distributeReward`


# v9.1.1 Update

## Summary

* Apply fee tiers to oracle rewards

## Full Changelog

### core/facets/GNSPriceAggregator.sol (update)

* `getPrice` and `getLinkFee` now accept `_trader` argument

### interfaces/libraries/IPriceAggregatorUtils.sol (update)

* Adjusted `getPrice` and `getLinkFee` functions definitions
* Updated `PriceRequested` event: now emits trader address, and `collateralIndex`/`trader`/`pairIndex` are now the indexed properties (`orderType` and `job` no longer indexed)

### libraries/updateLeverage/UpdateLeverageLifecycles.sol (update)

* `_initiateRequest`: small adjustment to avoid stack too deep, now passes `_trade.user` to `getPrice`

### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (update)

* `_initiateRequest`: passes `_trade.user` to `getPrice`

### libraries/PriceAggregatorUtils.sol (update)

* Library is now external
* `getPrice` now accepts `_trader` argument, refreshes fee tier for `_trader` right before calculating link fee, passes `_trader` to `getLinkFee` to apply his fee tier to the oracle link fees, and `PriceRequested` now emits `_trader`
* `getLinkFee` now accepts `_trader` and applies his fee tier to the link fee result

### libraries/TradingInteractionsUtils.sol (update)

* `closeTradeMarket`: passes `t.user` to `getPrice`
* `triggerOrder`: refreshes `t.user`'s fee tier before receiving the link fee from the caller, passes `t.user` to `getLinkFee`
* `_openTrade`: passes `_trade.user` to `getPrice`
* `_getPriceTriggerOrder`: passes `_trade.user` to `getPrice`


# v9 Update

## Summary

* New features: update trade leverage, update trade position size
* Important changes: min position size requirement replaced by minimum fee (trade collateral must be >= 5x min fee when opening), liquidation price now takes into account closing fees, getPnlPercent negative PnL capped at -100%
* Important refactors: TradingStorageUtils now handles all OI update calls, constants all moved to ConstantsUtils, common helpers moved to TradingCommonUtils, removed GNSTradingStateCopy facet, tradeInfo.collateralPriceUsd/tradeInfo.lastOiUpdateTs values now set in GNSPriceImpact.addPriceImpactOpenInterest instead of GNSTradingStorage.storeTrade
* Bugfixes: liquidation fees now don't take into account fee tiers, getTradeValuePure returns 0 for liquidations (due to precision loss it was possible liquidation price was reached but pnl + borrowing fees didn't reach -90% PnL), and \_openTrade now hardcodes \_trade.\_\_placeholder input to 0

## Full Changelog

### core/facets/GNSBorrowingFees (update)

* New resetTradeBorrowingFees function (pending borrowing fees are charged and reset on partial updates)

### core/facets/GNSPairsStorage (update)

* New pairMinFeeUsd getter function (trade fee at minimum position size, replaces minimum position size requirement)

### core/facets/GNSPriceImpact (update)

* addPriceImpactOpenInterest and removePriceImpactOpenInterest now accept trader/index/oi delta in collateral tokens oi delta in USD/pairIndex/long, and removePriceImpactOpenInterest no longer accepts \_addTs
* Added getTradeLastWindowOiUsd and getTradePriceImpactInfo getters

### core/facets/GNSTradingCallbacks (update)

* New callback functions for partials: updateLeverageCallback, increasePositionSizeMarketCallback, decreasePositionSizeMarketCallback

### core/facets/GNSTradingInteractions (update)

* New functions to initiate partial updates: updateLeverage, increasePositionSize, decreasePositionSize
* openTradeMarketTimeout and closeTradeMarketTimeout turned into cancelOrderAfterTimeout (supports all market order types including partials)

### core/facets/GNSTradingStateCopy.sol (removed)

* Not needed anymore now that v8 transition is done

### core/facets/GNSTradingStorage (update)

* New updateTradePosition function to update a trade's collateral, leverage, and open price
* Array getters (eg. getTraders) now call the new ArrayGetters library
* getPnlPercent function removed (moved to TradingCommonUtils)
* getPendingOpenOrderType moved to ConstantsUtils

### interfaces/libraries/IBorrowingFeesUtils.sol (update)

* BorrowingInitialAccFeesStored event now emits whether trade is long or short

### interfaces/libraries/IPriceImpactUtils.sol (update)

* PriceImpactOpenInterestAdded event now emits isPartial

### interfaces/libraries/ITradingCallbacksUtils.sol (update)

* Now inherits IUpdateLeverageUtils (leverage updates types and events), IUpdatePositionSizeUtils (position size updates types and events), and ITradingCommonUtils (fee charged events), so that IGNSMultiCollatDiamond also inherits those
* Fee charged events moved to ITradingCommonUtils because all functions that charge fees were moved there (since now they're used in many different places other than TradingCallbacksUtils, eg. partials libraries)

### interfaces/libraries/ITradingCommonUtils.sol (new)

* Contains fee charged events

### interfaces/libraries/ITradingInteractionsUtils.sol (update)

* Now inherits IUpdateLeverageUtils (leverage updates types and events), IUpdatePositionSizeUtils (position size updates types and events)
* AbovePairMaxOi and AboveGroupMaxOi errors consolidated into AboveExposureLimits, BelowMinPositionSizeUsd error removed, added ConflictingPendingOrder (eg. when trying to close trade that has a pending partial update) and InsufficientCollateral (trade collateral < 5 \* min fee when opening trade) errors

### interfaces/libraries/ITradingStateCopyUtils.sol (removed)

* Not needed anymore now that v8 transition is done

### interfaces/libraries/ITradingStorageUtils.sol (update)

* Removed getPendingOpenOrderType (moved to ConstantsUtils)
* Added TradePositionUpdated event

### interfaces/libraries/IUpdateLeverageUtils.sol (new)

* Contains update leverage events (LeverageUpdateInitiated, LeverageUpdateExecuted) and inherits IUpdateLeverage for types

### interfaces/libraries/IUpdatePositionSizeUtils.sol (new)

* Contains update position size events (PositionSizeUpdateInitiated, PositionSizeIncreaseExecuted, PositionSizeDecreaseExecuted) and inherits IUpdatePositionSize for types

### interfaces/types/IBorrowingFees.sol (update)

* Added useBorrowingFees property to LiqPriceInput struct (in increase position size callback we calculate new liq price using new leverage and collateral (- borrowing fees) but borrowing fees haven't been reset yet so we pass useBorrowingFees=false, all other calls pass true)

### interfaces/types/IPriceImpact.sol (update)

* New tradePriceImpactInfos mapping
* OiWindowUpdate struct (used for events) now also has trader and index properties
* New TradePriceImpactInfo struct to store lastWindowOiUsd (and potentially more, has a placeholder)

### interfaces/types/ITradingCallbacks.sol (update)

* Added LIQ\_REACHED to CancelReason enum (we cancel all partial updates if existing/updated trade can be liquidated)
* Added closingFeeCollateral, triggerFeeCollateral, and collateralLeftInStorage to Values struct

### interfaces/types/ITradingStateCopy.sol (removed)

* Not needed anymore now that v8 transition is done

### interfaces/types/ITradingStorage.sol (update)

* Added UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE values to PendingOrderType enum

### interfaces/types/IUpdateLeverage.sol (new)

* Contains useful structs for leverage updates (UpdateLeverageInput for request, UpdateLeverageValues for callback)

### interfaces/types/IUpdatePositionSize.sol (new)

* Contains useful structs for position size updates (DecreasePositionSizeInput and IncreasePositionSizeInput for request, DecreasePositionSizeValues and IncreasePositionSizeValues for callback)

### libraries/ArrayGetters.sol (new)

* New external library to reduce TradingStorageUtils size
* Array getters are what take the most amount of bytecode in a contract generally, so if needed we can move them in this new library
* For now only contains array getters of TradingStorageUtils but it could contain getters of other facets if needed too

### libraries/BorrowingFeesUtils.sol (update)

* LIQ\_THRESHOLD\_P AND P\_1 removed, replaced by ConstantsUtils.LIQ\_THRESHOLD\_P and ConstantsUtils.P\_10 respectively (same values)
* handleTradeBorrowingCallback: initial acc fees initalization when \_open = true replaced by resetTradeBorrowingFees call
* New resetTradeBorrowingFees function to reset a trade's borrowing fees to 0 by setting its initial acc fees to current acc pair/group borrowing fees, useful after partial updates since we charge pending borrowing fees and after we need to reset them to 0 to not charge them again later
* getTradeLiquidationPrice now calculates and passes closing fees to \_getTradeLiquidationPrice, and logic adjusted for \_input.useBorrowingFees (if false, passes 0 borrowing fees to \_getTradeLiquidationPrice)
* \_getTradeLiquidationPrice's \_borrowingFeeCollateral input renamed to \_feesCollateral, now expects closing fees + borrowing fees instead of just borrowing fees, but calculations stay the same

### libraries/ConstantsUtils.sol (new)

* New internal library for useful constants (P\_10, MAX\_SL\_P, MAX\_PNL\_P, LIQ\_THRESHOLD\_P, MAX\_OPEN\_NEGATIVE\_PNL\_P)
* Values for these constants didn't change, they were just moved to this library

### libraries/PairsStorageUtils.sol (update)

* Added pairMinFeeUsd getter, uses gov fee \* 2 + trigger fee on min position size usd (eg. 0.08% on crypto)

### libraries/PriceAggregatorUtils.sol (update)

* PRECISION constant replaced by ConstantsUtils.P\_10
* getPrice: isLookback is now equal to !ConstantsUtils.isOrderTypeMarket
* fulfill: added new callbacks for UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE order types (explicit check)
* getLinkFee: when \_positionSizeCollateral > 0 (doesn't bypass trigger link fee) uses TradingCommonUtils.getPositionSizeCollateralBasis to charge pairOracleFeeP on max(pos size, min pos size)

### libraries/PriceImpactUtils.sol (update)

* Replaced PRECISION by ConstantsUtils.P\_10
* addPriceImpactOpenInterest: arguments changed from \_openInterestUsd/\_pairIndex/\_long to \_trader/\_index/\_oiDeltaCollateral, now responsible for converting the collateral OI passed to USD value using current collateral/usd price, added logic for partials: if last window where OI was added for trade hasn't expired then remove OI from that window and add move it to the current window scaling to the new collateral/usd price, now responsible (instead of GNSTradingStorage) for setting tradeInfo.lastOiUpdateTs and tradeInfo.collateralPriceUsd, and finally stores the new tradePriceImpactInfo.lastWindowOiUsd value
* removePriceImpactOpenInterest: arguments changed from \_openInterestUsd/\_pairIndex/\_long/\_addTs to \_trader/\_index/\_oiDeltaCollateral, now fetches timestamp when OI was last added from within the function using tradeInfo.lastOiUpdateTs, responsible for converting the OI collateral value input to USD using tradeInfo.collateralPriceUsd, now caps the removal of OI to the new lastWindowOiUsd value (since any trade OI that's not part of lastWindowOiUsd has necessarily expired and is in another older window), and reduces lastWindowOiUsd by the oi delta so it stays accurate
* New getTradeLastWindowOiUsd getter that simply returns lastWindowOiUsd when it's set to a value > 0, otherwise returns the USD position size of the trade at the time of opening (useful for trades opened before v9)
* New getTradePriceImpactInfo getter to return values of the new mapping

### libraries/ReferralsUtils.sol (update)

* Replaced PRECISION by ConstantsUtils.P\_10

### libraries/TradingCallbacksUtils.sol (update)

* PRECISION replaced by ConstantsUtils.P\_10, LIQ\_THRESHOLD\_P by ConstantsUtils.LIQ\_THRESHOLD\_P, and MAX\_OPEN\_NEGATIVE\_PNL\_P by ConstantsUtils.MAX\_OPEN\_NEGATIVE\_PNL\_P
* \_transferCollateralToAddress replaced by TradingCommonUtils.transferCollateralTo, \_updateTraderPoints replaced by TradingCommonUtils.updateFeeTierPoints, \_handleGovFees replaced by radingCommonUtils.distributeGovFeeCollateral, \_getPositionSizeCollateral replaced by TradingCommonUtils.getPositionSizeCollateral, diamond.getPnlPercent replaced by TradingCommonUtils.getPnlPercent, \_getTradeValue replaced by TradingCommonUtils.getTradeValueCollateral, \_marketExecutionPrice replaced by TradingCommonUtils.getMarketExecutionPrice, \_withinExposureLimits replaced by TradingCommonUtils.isWithinExposureLimits
* When a trade is canceled (openTradeMarketCallback, closeTradeMarketCallback) we charge gov fee on min pos size / 2 instead of gov fee on full position size
* closeTradeMarketCallback: v.positionSizeCollateral removed (was used to calculate closing fees), closing fees calculation moved to inside \_unregisterTrade, removed OI removal when canceled (now handled inside GNSTradingStorage.updateTradeCollateralAmount)
* executeTriggerCloseOrderCallback: v.positionSizeCollateral removed (was used to calculate closing fees), v.liqPrice uses TradingCommonUtils wrapper, v.reward1 calculation removed (now done inside \_unregisterTrade) and same conditions used to determine cancelReason directly instead, removed v.gnsPriceCollateral (unused), just pass order type to \_unregisterTrade instead of closing fees, no longer call \_handleTriggerRewards (done from within \_unregisterTrade depending on orderType)
* Added: updateLeverageCallback (tradingActivated modifier), increasePositionSizeMarketCallback (tradingActivated modifier), decreasePositionSizeMarketCallback (tradingActivatedOrCloseOnly modifier) for partials, they just return early if order is not open like for other callbacks and call the corresponding UpdateLeverageLifecycles/UpdatePositionSizeLifecycles execute callback function
* Removed: \_transferCollateralToAddress, \_distributeStakingReward, \_sendToVault, \_handleTriggerRewards, \_handleGovFees, \_updateTraderPoints, \_distributeReferralReward, \_handleInternalOnRegisterUpdates, \_convertCollateralToUsd, \_convertCollateralToGns, \_getTradeValuePure, \_marketExecutionPrice, \_getTradeValue, \_withinExposureLimits, \_getGToken, \_getPositionSizeCollateral (all moved/refactored to TradingCommonUtils)
* \_registerTrade: simplified a lot, all opening fees calculations / distributions moved to TradingCommonUtils.processOpeningFees, \_handleInternalOnRegisterUpdates call removed as GNSTradingStorage manages OI deltas now (directly in storeTrade)
* \_unregisterTrade: \_marketOrder input replaced by \_orderType, no longer accepts closing fees as input, moved fee tier closing fees calculations/gToken fee distribution/GNS staking fee distribution/collateralLeftInStorage calculation to TradingCommonUtils.processClosingFees, removed handleTradeBorrowingCallback/removePriceImpactOpenInterest calls as GNSTradingStorage.closeTrade now handles OI deltas, now calls TradingCommonUtils.handleTradePnl for PnL/collateral transfers logic
* \_openTradePrep: pass positionSizeCollateral to isWithinExposureLimits instead of collateral and leverage

### libraries/TradingCommonUtils.sol (new)

* New external library that contains helpers called by multiple libraries
* Contains useful getters (pnl, position size, etc.), collateral/pnl transfer functions, fee distributions, OI delta handling
* Mostly renames of previous private functions in TradingCallbacksUtils and TradingInteractionsUtils
* getPnlPercent: now caps negative PnL at -100%
* getMinPositionSizeCollateral: new function that converts min pos usd to min pos collateral and returns it
* getPositionSizeCollateralBasis: returns max(position size input, min position size collateral) for fees calculations
* getTradeValuePure: accepts \_orderType and returns 0 if liquidation, now takes into account closing fees for liquidation threshold
* isWithinExposureLimits: now accepts \_positionSizeCollateralDelta instead of trade collateral and leverage (so it works for partials too)
* getTradeBorrowingFeeCollateral: useful wrapper that takes trade struct as input
* getTradeLiquidationPrice: same just a wrapper that takes trade struct as input
* getGovFeeCollateral: new getter that returns gov fee after fee tier based on position size
* getClosingFeesCollateral: new getter that returns vault and gns staking fees based on closing fee/trigger fee/order type
* revertIfTradeHasPendingMarketOrder: new helper to prevent two pending market orders on the same trade
* transferCollateralFrom: new helper to transfer collateral from trader to diamond if amount > 0
* handleTradePnl: new helper to handle collateral/pnl transfers between vault/diamond and trader (used for full closes and partial closes)
* distributeVaultFeeCollateral: new helper to distribute vault reward
* distributeExactGovFeeCollateral: new helper to distribute an exact amount of gov fee
* processOpeningFees: new helper that contains the previous fee calculation / distribution logic of \_registerTrade used for both full and partial trade open and returns the total opening fee charged (difference is it charges fees on max(position size input, min position size) and it uses !ConstantsUtils.isOrderTypeMarket to know if it should distribute the trigger fee)
* processClosingFees: new helper that contains the previous fee calculation / distribution logic of \_unregisterTrade used for full trade closes only and returns the value struct with the fee values and collateralLeftInStorage (difference is it charges fees on max(position size input, min position size), it calculates the closing and trigger fees based on the order type (and only applies fee tier if order type is not liquidation), it calculates the vault and gns staking fees by calling getClosingFeesCollateral, it only distributes the gns staking and vault fees if trade collateral is big enough to pay (otherwise it's still charged but as negative PnL only), and it distributes the trigger gns fee depending on the order type using !ConstantsUtils.isOrderTypeMarket)
* addOiCollateral: new helper to add borrowing/price impact windows OI in one call (flexible amount)
* addTradeOiCollateral: new helper to add borrowing/price impact windows OI in one call (trade position size)
* removeOiCollateral: new helper to remove borrowing/price impact windows OI in one call (flexible amount)
* removeTradeOiCollateral: new helper to remove borrowing/price impact windows OI in one call (trade position size)
* handleOiDelta: new helper that either calls addOiCollateral or removeOiCollateral based on a trade's new position size and its existing position size

### libraries/TradingInteractionsUtils.sol (update)

* PRECISION replaced by ConstantsUtils.P\_10, MAX\_SL\_P replaced by ConstantsUtils.MAX\_SL\_P, and MAX\_OPEN\_NEGATIVE\_PNL\_P replaced by ConstantsUtils.MAX\_OPEN\_NEGATIVE\_PNL\_P
* getPendingOrderType calls now use ConstantsUtils
* Replaced \_getPositionSizeCollateral by TradingCommonUtils.getPositionSizeCollateral, \_transferCollateralToTrader by TradingCommonUtils.transferCollateralTo, and \_receiveCollateralFromTrader by TradingCommonUtils.transferCollateralFrom (those 3 private functions were removed)
* closeTradeMarket: Replace AlreadyBeingMarketClosed() check by TradingCommonUtils.revertIfTradeHasPendingMarketOrder call
* Added: updateLeverage, increasePositionSize, decreasePositionSize that call the create request function in their lifecycles library
* triggerOrder: use TradingCommonUtils.getTradeLiquidationPrice wrapper
* openTradeMarketTimeout/closeTradeMarketTimeout: removed in favor of cancelOrderAfterTimeout which only accepts an order index now instead of the full order id (impossible to input another address than yours, removes need for this check)
* triggerOrder: use ConstantsUtils.isOrderTypeMarket for WrongOrderType check
* cancelOrderAfterTimeout: Supports all market orders (ConstantsUtils.isOrderTypeMarket), transfers back trade collateral for MARKET\_OPEN, transfers back partial collateral for UPDATE\_LEVERAGE (leverage decrease), and transfers back partial collateral for MARKET\_PARTIAL\_OPEN (no longer calls closeTradeMarket() again for MARKET\_CLOSE orders)
* \_openTrade: overwrite \_trade.\_\_placeholder to 0, consolidated AbovePairMaxOi and AboveGroupMaxOi checks into AboveExposureLimits using TradingCommonUtils.isWithinExposureLimits, replaced BelowMinPositionSizeUsd check by InsufficientCollateral (trade collateral must be >= min fee)

### libraries/TradingStateCopyUtils.sol (removed)

* Not needed anymore now that v8 transition is done

### libraries/TradingStorageUtils.sol (update)

* Turned into external library (otherwise GNSTradingStorage facet contract would be above max limit)
* PRICE\_PRECISION replaced by ConstantsUtils.P\_10, MAX\_SL\_P replaced by ConstantsUtils.MAX\_SL\_P, MAX\_PNL\_P not used anymore
* storeTrade: removed TradeInfoCollateralPriceUsdZero check (now tradeInfo.collateralPriceUsd is set by GNSPriceImpact.addPriceImpactOpenInterest), enforces \_tradeInfo.lastOiUpdateTs to 0 to make sure isPartial = false when calling addPriceImpactOpenInterest, added TradingCommonUtils.addTradeOiCollateral call when tradeType is TRADE
* updateTradeCollateralAmount: added TradingCommonUtils.handleOiDelta call, added i.createdBlock update (because reducing a trade's collateral now potentially changes the trade's liquidation price with the liq price taking into account closing fees and closing fees having a minimum value)
* updateTradePosition: new helper to update a trade's collateralAmount/leverage/openPrice, same checks as updateTradeCollateralAmount (trade must be open, trade type must be TRADE, and additionally new collateral \* new leverage > 0 and new openPrice > 0) calls \_limitTpDistance and \_limitSlDistance again based on updated values, updates i.createdBlock/tpLastUpdatedBlock/slLastUpdatedBlock so lookbacks work properly (tp/sl potentially updated, liquidation price updated)
* closeTrade: added TradingCommonUtils.removeTradeOiCollateral call when tradeType is TRADE
* Array getters (getTraders, getTrades, getAllTrades, getTradeInfos, getAllTradeInfos, getPendingOrders, getAllPendingOrders) moved to new ArrayGetters external library
* getPnlPercent moved to TradingCommonUtils
* \_validateTrade: use TradingCommonUtils.getPositionSizeCollateral
* Removed getPendingOpenOrderType (moved to ConstantsUtils)

### libraries/updateLeverage/UpdateLeverageLifecycles.sol (new)

* New external library to handle leverage updates lifecycles
* requestUpdateLeverage: create request (used by TradingInteractionsUtils)
* executeUpdateLeverage: callback (used by TradingCallbacksUtils)

### libraries/updatePositionSize/DecreasePositionSizeUtils.sol (new)

* New internal library to handle position size decreases, used by the new UpdatePositionSizeLifecycles library
* validateRequest: request validation, prepareCallbackValues: all the calculations, validateCallback: callback validation, updateTradeSuccess: success callback, handleCanceled: canceled callback

### libraries/updatePositionSize/IncreasePositionSizeUtils.sol (new)

* New internal library to handle position size increases, used by the new UpdatePositionSizeLifecycles library
* validateRequest: request validation, prepareCallbackValues: all the calculations, validateCallback: callback validation, updateTradeSuccess: success callback, handleCanceled: canceled callback

### libraries/updatePositionSize/UpdatePositionSizeLifecycles.sol (new)

* New external library to handle position size updates lifecycles
* requestIncreasePositionSize: create position size increase request (used by TradingInteractionsUtils)
* requestDecreasePositionSize: create position size decrease request (used by TradingInteractionsUtils)
* executeIncreasePositionSizeMarket: increase position size callback (used by TradingCallbacksUtils)
* executeDecreasePositionSizeMarket: decrease position size callback (used by TradingCallbacksUtils)


# Core


# Abstract


# GNSAddressStore

*Proxy base for the diamond and its facet contracts to store addresses and manage access control*

## initialize

```solidity
function initialize(address _rolesManager) external
```

*Initializes address store facet*

### Parameters

| Name           | Type    | Description           |
| -------------- | ------- | --------------------- |
| \_rolesManager | address | roles manager address |

## getAddresses

```solidity
function getAddresses() external view returns (struct IAddressStore.Addresses)
```

*Returns addresses current values*

## hasRole

```solidity
function hasRole(address _account, enum IAddressStore.Role _role) public view returns (bool)
```

*Returns whether an account has been granted a particular role*

### Parameters

| Name      | Type                    | Description              |
| --------- | ----------------------- | ------------------------ |
| \_account | address                 | account address to check |
| \_role    | enum IAddressStore.Role | role to check            |

## \_setRole

```solidity
function _setRole(address _account, enum IAddressStore.Role _role, bool _value) internal
```

*Update role for account*

### Parameters

| Name      | Type                    | Description                   |
| --------- | ----------------------- | ----------------------------- |
| \_account | address                 | account to update             |
| \_role    | enum IAddressStore.Role | role to set                   |
| \_value   | bool                    | true if allowed, false if not |

## setRoles

```solidity
function setRoles(address[] _accounts, enum IAddressStore.Role[] _roles, bool[] _values) external
```

*Updates access control for a list of accounts*

### Parameters

| Name       | Type                       | Description                     |
| ---------- | -------------------------- | ------------------------------- |
| \_accounts | address\[]                 | accounts addresses to update    |
| \_roles    | enum IAddressStore.Role\[] | corresponding roles to update   |
| \_values   | bool\[]                    | corresponding new values to set |

## \_enforceRole

```solidity
function _enforceRole(enum IAddressStore.Role _role) internal view
```

*Reverts if caller does not have role*

### Parameters

| Name   | Type                    | Description     |
| ------ | ----------------------- | --------------- |
| \_role | enum IAddressStore.Role | role to enforce |

## onlyRole

```solidity
modifier onlyRole(enum IAddressStore.Role _role)
```

*Reverts if caller does not have role*

## onlySelf

```solidity
modifier onlySelf()
```

*Reverts if caller isn't this same contract (facets calling other facets)*


# GNSDiamondCut

*Based on EIP-2535: Diamonds (*[*https://eips.ethereum.org/EIPS/eip-2535*](https://eips.ethereum.org/EIPS/eip-2535)*) Follows diamond-3 implementation (*[*https://github.com/mudgen/diamond-3-hardhat/*](https://github.com/mudgen/diamond-3-hardhat/)*) Manages all actions (calls, updates and initializations) related to the diamond and its facets.*

## fallback

```solidity
fallback() external payable
```

*Forwards call to the right facet using msg.sig using delegatecall. Reverts if signature is not known.*

## receive

```solidity
receive() external payable
```

*Allows the contract to receive ether*

## diamondCut

```solidity
function diamondCut(struct IDiamondStorage.FacetCut[] _faceCut, address _init, bytes _calldata) external
```

Add/replace/remove any number of functions and optionally execute a function with delegatecall

### Parameters

| Name       | Type                                                                                                               | Description                                                                                                   |
| ---------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| \_faceCut  | [IDiamondStorage.FacetCut\[\]](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#facetcut) |                                                                                                               |
| \_init     | address                                                                                                            | The address of the contract or facet to execute \_calldata                                                    |
| \_calldata | bytes                                                                                                              | A function call, including function selector and arguments \_calldata is executed with delegatecall on \_init |

## \_diamondCut

```solidity
function _diamondCut(struct IDiamondStorage.FacetCut[] _facetCut, address _init, bytes _calldata) internal
```

*Internal function for diamondCut()*

## \_addFunctions

```solidity
function _addFunctions(address _facetAddress, bytes4[] _functionSelectors) internal
```

*Adds the facet if it wasn't added yet, and adds its functions to the diamond*

### Parameters

| Name                | Type      | Description                   |
| ------------------- | --------- | ----------------------------- |
| \_facetAddress      | address   | address of the facet contract |
| \_functionSelectors | bytes4\[] | array of function selectors   |

## \_replaceFunctions

```solidity
function _replaceFunctions(address _facetAddress, bytes4[] _functionSelectors) internal
```

*Updates facet contract address for given function selectors*

### Parameters

| Name                | Type      | Description                   |
| ------------------- | --------- | ----------------------------- |
| \_facetAddress      | address   | address of the facet contract |
| \_functionSelectors | bytes4\[] | array of function selectors   |

## \_removeFunctions

```solidity
function _removeFunctions(address _facetAddress, bytes4[] _functionSelectors) internal
```

*Removes some function selectors of a facet from diamond*

### Parameters

| Name                | Type      | Description                   |
| ------------------- | --------- | ----------------------------- |
| \_facetAddress      | address   | address of the facet contract |
| \_functionSelectors | bytes4\[] | array of function selectors   |

## \_addFacet

```solidity
function _addFacet(struct IDiamondStorage.DiamondStorage s, address _facetAddress) internal
```

*Adds a new facet contract address to the diamond*

### Parameters

| Name           | Type                                                                                                                       | Description                       |
| -------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| s              | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer           |
| \_facetAddress | address                                                                                                                    | address of the new facet contract |

## \_addFunction

```solidity
function _addFunction(struct IDiamondStorage.DiamondStorage s, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal
```

*Adds a new function to the diamond for a given facet contract*

### Parameters

| Name               | Type                                                                                                                       | Description                                                    |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| s                  | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer                                        |
| \_selector         | bytes4                                                                                                                     | function selector                                              |
| \_selectorPosition | uint96                                                                                                                     | position of the function selector in the facet selectors array |
| \_facetAddress     | address                                                                                                                    | address of the facet contract                                  |

## \_removeFunction

```solidity
function _removeFunction(struct IDiamondStorage.DiamondStorage s, address _facetAddress, bytes4 _selector) internal
```

*Removes a function from a facet of the diamond*

### Parameters

| Name           | Type                                                                                                                       | Description                   |
| -------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| s              | [IDiamondStorage.DiamondStorage](/developer/technical-reference/contracts/interfaces/types/idiamondstorage#diamondstorage) | diamond storage pointer       |
| \_facetAddress | address                                                                                                                    | address of the facet contract |
| \_selector     | bytes4                                                                                                                     | function selector             |

## \_initializeDiamondCut

```solidity
function _initializeDiamondCut(address _init, bytes _calldata) internal
```

*Initializes a facet after updating the diamond using delegatecall*

### Parameters

| Name       | Type    | Description                                   |
| ---------- | ------- | --------------------------------------------- |
| \_init     | address | address of the contract to execute \_calldata |
| \_calldata | bytes   | function call (selector and arguments)        |

## \_enforceHasContractCode

```solidity
function _enforceHasContractCode(address _contract) internal view
```

*Reverts if the given address is not a contract*

### Parameters

| Name       | Type    | Description      |
| ---------- | ------- | ---------------- |
| \_contract | address | address to check |


# GNSDiamondLoupe

*Based on EIP-2535: Diamonds (<https://eips.ethereum.org/EIPS/eip-2535>) Follows diamond-3 implementation (<https://github.com/mudgen/diamond-3-hardhat/>) Returns useful information about the diamond and its facets.*

## facets

```solidity
function facets() external view returns (struct IGNSDiamondLoupe.Facet[] facets_)
```

Gets all facets and their selectors.

### Return Values

| Name     | Type                                                                                                     | Description |
| -------- | -------------------------------------------------------------------------------------------------------- | ----------- |
| facets\_ | [IGNSDiamondLoupe.Facet\[\]](/developer/technical-reference/contracts/interfaces/ignsdiamondloupe#facet) | Facet       |

## facetFunctionSelectors

```solidity
function facetFunctionSelectors(address _facet) external view returns (bytes4[] facetFunctionSelectors_)
```

Gets all the function selectors provided by a facet.

### Parameters

| Name    | Type    | Description        |
| ------- | ------- | ------------------ |
| \_facet | address | The facet address. |

### Return Values

| Name                     | Type      | Description             |
| ------------------------ | --------- | ----------------------- |
| facetFunctionSelectors\_ | bytes4\[] | the function selectors. |

## facetAddresses

```solidity
function facetAddresses() external view returns (address[] facetAddresses_)
```

Get all the facet addresses used by a diamond.

### Return Values

| Name             | Type       | Description         |
| ---------------- | ---------- | ------------------- |
| facetAddresses\_ | address\[] | the facet addresses |

## facetAddress

```solidity
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_)
```

Gets the facet that supports the given selector.

*If facet is not found return address(0).*

### Parameters

| Name               | Type   | Description            |
| ------------------ | ------ | ---------------------- |
| \_functionSelector | bytes4 | The function selector. |

### Return Values

| Name           | Type    | Description        |
| -------------- | ------- | ------------------ |
| facetAddress\_ | address | The facet address. |


# GNSDiamondStorage

*Sets storage slot layout for diamond facets.*


# Facets


# GNSBorrowingFees

*Facet #9: Borrowing Fees and open interests*

## constructor

```solidity
constructor() public
```

## setBorrowingPairParams

```solidity
function setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) external
```

*Updates borrowing pair params of a pair*

### Parameters

| Name              | Type                                                                                                                               | Description             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                              | index of the collateral |
| \_pairIndex       | uint16                                                                                                                             | index of the pair       |
| \_value           | [IBorrowingFees.BorrowingPairParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new value               |

## setBorrowingPairParamsArray

```solidity
function setBorrowingPairParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingPairParams[] _values) external
```

*Updates borrowing pair params of multiple pairs*

### Parameters

| Name              | Type                                                                                                                                   | Description             |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                                  | index of the collateral |
| \_indices         | uint16\[]                                                                                                                              | indices of the pairs    |
| \_values          | [IBorrowingFees.BorrowingPairParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new values              |

## setBorrowingGroupParams

```solidity
function setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) external
```

*Updates borrowing group params of a group*

### Parameters

| Name              | Type                                                                                                                                 | Description                  |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| \_collateralIndex | uint8                                                                                                                                | index of the collateral      |
| \_groupIndex      | uint16                                                                                                                               | index of the borrowing group |
| \_value           | [IBorrowingFees.BorrowingGroupParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new value                    |

## setBorrowingGroupParamsArray

```solidity
function setBorrowingGroupParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingGroupParams[] _values) external
```

*Updates borrowing group params of multiple groups*

### Parameters

| Name              | Type                                                                                                                                     | Description             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                                    | index of the collateral |
| \_indices         | uint16\[]                                                                                                                                | indices of the groups   |
| \_values          | [IBorrowingFees.BorrowingGroupParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new values              |

## handleTradeBorrowingCallback

```solidity
function handleTradeBorrowingCallback(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, uint256 _positionSizeCollateral, bool _open, bool _long) external virtual
```

*Callback after a trade is opened/closed to store pending borrowing fees and adjust open interests*

### Parameters

| Name                     | Type    | Description                                                   |
| ------------------------ | ------- | ------------------------------------------------------------- |
| \_collateralIndex        | uint8   | index of the collateral                                       |
| \_trader                 | address | address of the trader                                         |
| \_pairIndex              | uint16  | index of the pair                                             |
| \_index                  | uint32  | index of the trade                                            |
| \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens               |
| \_open                   | bool    | true if trade has been opened, false if trade has been closed |
| \_long                   | bool    | true if trade is long, false if trade is short                |

## resetTradeBorrowingFees

```solidity
function resetTradeBorrowingFees(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, bool _long) external virtual
```

*Resets a trade borrowing fee to 0 (useful when new trade opened or when partial trade executed)*

### Parameters

| Name              | Type    | Description                                    |
| ----------------- | ------- | ---------------------------------------------- |
| \_collateralIndex | uint8   | index of the collateral                        |
| \_trader          | address | address of the trader                          |
| \_pairIndex       | uint16  | index of the pair                              |
| \_index           | uint32  | index of the trade                             |
| \_long            | bool    | true if trade is long, false if trade is short |

## getBorrowingPairPendingAccFees

```solidity
function getBorrowingPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) public view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 pairAccFeeDelta)
```

*Returns the pending acc borrowing fees for a pair on both sides*

### Parameters

| Name              | Type    | Description             |
| ----------------- | ------- | ----------------------- |
| \_collateralIndex | uint8   | index of the collateral |
| \_pairIndex       | uint16  | index of the pair       |
| \_currentBlock    | uint256 | current block number    |

### Return Values

| Name            | Type   | Description                                          |
| --------------- | ------ | ---------------------------------------------------- |
| accFeeLong      | uint64 | new pair acc borrowing fee on long side              |
| accFeeShort     | uint64 | new pair acc borrowing fee on short side             |
| pairAccFeeDelta | uint64 | pair acc borrowing fee delta (for side that changed) |

## getBorrowingGroupPendingAccFees

```solidity
function getBorrowingGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) public view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 groupAccFeeDelta)
```

*Returns the pending acc borrowing fees for a borrowing group on both sides*

### Parameters

| Name              | Type    | Description                  |
| ----------------- | ------- | ---------------------------- |
| \_collateralIndex | uint8   | index of the collateral      |
| \_groupIndex      | uint16  | index of the borrowing group |
| \_currentBlock    | uint256 | current block number         |

### Return Values

| Name             | Type   | Description                                           |
| ---------------- | ------ | ----------------------------------------------------- |
| accFeeLong       | uint64 | new group acc borrowing fee on long side              |
| accFeeShort      | uint64 | new group acc borrowing fee on short side             |
| groupAccFeeDelta | uint64 | group acc borrowing fee delta (for side that changed) |

## getTradeBorrowingFee

```solidity
function getTradeBorrowingFee(struct IBorrowingFees.BorrowingFeeInput _input) public view returns (uint256 feeAmountCollateral)
```

*Returns the borrowing fee for a trade*

### Parameters

| Name    | Type                                                                                                                           | Description                                                                        |
| ------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| \_input | [IBorrowingFees.BorrowingFeeInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingfeeinput) | input data (collateralIndex, trader, pairIndex, index, long, collateral, leverage) |

### Return Values

| Name                | Type    | Description                          |
| ------------------- | ------- | ------------------------------------ |
| feeAmountCollateral | uint256 | borrowing fee (collateral precision) |

## getTradeLiquidationPrice

```solidity
function getTradeLiquidationPrice(struct IBorrowingFees.LiqPriceInput _input) external view returns (uint256)
```

*Returns the liquidation price for a trade*

### Parameters

| Name    | Type                                                                                                                   | Description                                                                                   |
| ------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| \_input | [IBorrowingFees.LiqPriceInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#liqpriceinput) | input data (collateralIndex, trader, pairIndex, index, openPrice, long, collateral, leverage) |

## getPairOisCollateral

```solidity
function getPairOisCollateral(uint8 _collateralIndex, uint16 _pairIndex) public view returns (uint256 longOi, uint256 shortOi)
```

*Returns the open interests for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

### Return Values

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| longOi  | uint256 | open interest on long side  |
| shortOi | uint256 | open interest on short side |

## getBorrowingPairGroupIndex

```solidity
function getBorrowingPairGroupIndex(uint8 _collateralIndex, uint16 _pairIndex) public view returns (uint16 groupIndex)
```

*Returns the borrowing group index for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

### Return Values

| Name       | Type   | Description           |
| ---------- | ------ | --------------------- |
| groupIndex | uint16 | borrowing group index |

## getPairOiCollateral

```solidity
function getPairOiCollateral(uint8 _collateralIndex, uint16 _pairIndex, bool _long) external view returns (uint256)
```

*Returns the open interest in collateral tokens for a pair on one side*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |
| \_long            | bool   | true if long side       |

## withinMaxBorrowingGroupOi

```solidity
function withinMaxBorrowingGroupOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateral) external view returns (bool)
```

*Returns whether a trade is within the max group borrowing open interest*

### Parameters

| Name                     | Type    | Description                                     |
| ------------------------ | ------- | ----------------------------------------------- |
| \_collateralIndex        | uint8   | index of the collateral                         |
| \_pairIndex              | uint16  | index of the pair                               |
| \_long                   | bool    | true if long side                               |
| \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens |

## getBorrowingGroup

```solidity
function getBorrowingGroup(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.BorrowingData)
```

*Returns a borrowing group's data*

### Parameters

| Name              | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| \_collateralIndex | uint8  | index of the collateral      |
| \_groupIndex      | uint16 | index of the borrowing group |

## getBorrowingGroupOi

```solidity
function getBorrowingGroupOi(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.OpenInterest)
```

*Returns a borrowing group's oi data*

### Parameters

| Name              | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| \_collateralIndex | uint8  | index of the collateral      |
| \_groupIndex      | uint16 | index of the borrowing group |

## getBorrowingPair

```solidity
function getBorrowingPair(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingData)
```

*Returns a borrowing pair's data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getBorrowingPairOi

```solidity
function getBorrowingPairOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.OpenInterest)
```

*Returns a borrowing pair's oi data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getBorrowingPairGroups

```solidity
function getBorrowingPairGroups(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingPairGroup[])
```

*Returns a borrowing pair's oi data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getAllBorrowingPairs

```solidity
function getAllBorrowingPairs(uint8 _collateralIndex) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[], struct IBorrowingFees.BorrowingPairGroup[][])
```

*Returns all borrowing pairs' borrowing data, oi data, and pair groups data*

### Parameters

| Name              | Type  | Description             |
| ----------------- | ----- | ----------------------- |
| \_collateralIndex | uint8 | index of the collateral |

## getBorrowingGroups

```solidity
function getBorrowingGroups(uint8 _collateralIndex, uint16[] _indices) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[])
```

*Returns borrowing groups' data and oi data*

### Parameters

| Name              | Type      | Description             |
| ----------------- | --------- | ----------------------- |
| \_collateralIndex | uint8     | index of the collateral |
| \_indices         | uint16\[] | indices of the groups   |

## getBorrowingInitialAccFees

```solidity
function getBorrowingInitialAccFees(uint8 _collateralIndex, address _trader, uint32 _index) external view returns (struct IBorrowingFees.BorrowingInitialAccFees)
```

*Returns borrowing groups' data*

### Parameters

| Name              | Type    | Description             |
| ----------------- | ------- | ----------------------- |
| \_collateralIndex | uint8   | index of the collateral |
| \_trader          | address | address of trader       |
| \_index           | uint32  | index of trade          |

## getPairMaxOi

```solidity
function getPairMaxOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256)
```

*Returns the max open interest for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getPairMaxOiCollateral

```solidity
function getPairMaxOiCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256)
```

*Returns the max open interest in collateral tokens for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |


# GNSOtc

*Facet #11: OTC (Handles buy backs and distribution)*

## constructor

```solidity
constructor() public
```

## initializeOtc

```solidity
function initializeOtc(struct IOtc.OtcConfig _config) external
```

*Initializer for OTC facet*

### Parameters

| Name     | Type                                                                                       | Description    |
| -------- | ------------------------------------------------------------------------------------------ | -------------- |
| \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config |

## updateOtcConfig

```solidity
function updateOtcConfig(struct IOtc.OtcConfig _config) external
```

*Updates OTC config*

### Parameters

| Name     | Type                                                                                       | Description                                                                                                                                        |
| -------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config. Sum of `treasuryShareP`, `stakingShareP`, `burnShareP` must equal 100 and `premiumP` must be less than or equal to MAX\_PREMIUM\_P |

## addOtcCollateralBalance

```solidity
function addOtcCollateralBalance(uint8 _collateralIndex, uint256 _collateralAmount) external virtual
```

*Increases OTC balance for a collateral*

### Parameters

| Name               | Type    | Description                                             |
| ------------------ | ------- | ------------------------------------------------------- |
| \_collateralIndex  | uint8   | collateral index                                        |
| \_collateralAmount | uint256 | amount of collateral to increase (collateral precision) |

## sellGnsForCollateral

```solidity
function sellGnsForCollateral(uint8 _collateralIndex, uint256 _collateralAmount) external
```

*OTC Buys GNS from caller for `_amountCollateral` of `_collateralIndex`*

### Parameters

| Name               | Type    | Description                                          |
| ------------------ | ------- | ---------------------------------------------------- |
| \_collateralIndex  | uint8   | collateral index                                     |
| \_collateralAmount | uint256 | amount of collateral to trade (collateral precision) |

## getOtcConfig

```solidity
function getOtcConfig() external view returns (struct IOtc.OtcConfig)
```

*Returns OTC Config*

## getOtcBalance

```solidity
function getOtcBalance(uint8 _collateralIndex) external view returns (uint256)
```

*Returns OTC balance for a collateral (collateral precision)*

### Parameters

| Name              | Type  | Description      |
| ----------------- | ----- | ---------------- |
| \_collateralIndex | uint8 | collateral index |

## getOtcRate

```solidity
function getOtcRate(uint8 _collateralIndex) external view returns (uint256)
```

*Returns OTC rate (price + premium) of GNS in collateral (1e10)*

### Parameters

| Name              | Type  | Description      |
| ----------------- | ----- | ---------------- |
| \_collateralIndex | uint8 | collateral index |


# GNSPriceAggregator

*Facet #10: Price aggregator (does the requests to the Chainlink DON, takes the median, and executes callbacks)*

## constructor

```solidity
constructor() public
```

## initializePriceAggregator

```solidity
function initializePriceAggregator(address _linkToken, contract IChainlinkFeed _linkUsdPriceFeed, uint24 _twapInterval, uint8 _minAnswers, address[] _nodes, bytes32[2] _jobIds, uint8[] _collateralIndices, struct IPriceAggregator.LiquidityPoolInput[] _gnsCollateralLiquidityPools, contract IChainlinkFeed[] _collateralUsdPriceFeeds) external
```

*Initializes price aggregator facet*

### Parameters

| Name                          | Type                                                                                                                                     | Description                                            |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| \_linkToken                   | address                                                                                                                                  | LINK token address                                     |
| \_linkUsdPriceFeed            | contract IChainlinkFeed                                                                                                                  | LINK/USD price feed address                            |
| \_twapInterval                | uint24                                                                                                                                   | TWAP interval (seconds)                                |
| \_minAnswers                  | uint8                                                                                                                                    | answers count at which a trade is executed with median |
| \_nodes                       | address\[]                                                                                                                               |                                                        |
| \_jobIds                      | bytes32\[2]                                                                                                                              | chainlink job ids (market/lookback)                    |
| \_collateralIndices           | uint8\[]                                                                                                                                 | collateral indices                                     |
| \_gnsCollateralLiquidityPools | [IPriceAggregator.LiquidityPoolInput\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | corresponding GNS/collateral liquidity pool values     |
| \_collateralUsdPriceFeeds     | contract IChainlinkFeed\[]                                                                                                               | corresponding collateral/USD chainlink price feeds     |

## updateLinkUsdPriceFeed

```solidity
function updateLinkUsdPriceFeed(contract IChainlinkFeed _value) external
```

*Updates LINK/USD chainlink price feed*

### Parameters

| Name    | Type                    | Description |
| ------- | ----------------------- | ----------- |
| \_value | contract IChainlinkFeed | new value   |

## updateCollateralUsdPriceFeed

```solidity
function updateCollateralUsdPriceFeed(uint8 _collateralIndex, contract IChainlinkFeed _value) external
```

*Updates collateral/USD chainlink price feed*

### Parameters

| Name              | Type                    | Description      |
| ----------------- | ----------------------- | ---------------- |
| \_collateralIndex | uint8                   | collateral index |
| \_value           | contract IChainlinkFeed | new value        |

## updateCollateralGnsLiquidityPool

```solidity
function updateCollateralGnsLiquidityPool(uint8 _collateralIndex, struct IPriceAggregator.LiquidityPoolInput _liquidityPoolInput) external
```

*Updates collateral/GNS liquidity pool*

### Parameters

| Name                 | Type                                                                                                                                 | Description      |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------- |
| \_collateralIndex    | uint8                                                                                                                                | collateral index |
| \_liquidityPoolInput | [IPriceAggregator.LiquidityPoolInput](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | new values       |

## updateTwapInterval

```solidity
function updateTwapInterval(uint24 _twapInterval) external
```

*Updates TWAP interval*

### Parameters

| Name           | Type   | Description         |
| -------------- | ------ | ------------------- |
| \_twapInterval | uint24 | new value (seconds) |

## updateMinAnswers

```solidity
function updateMinAnswers(uint8 _value) external
```

*Updates minimum answers count*

### Parameters

| Name    | Type  | Description |
| ------- | ----- | ----------- |
| \_value | uint8 | new value   |

## addOracle

```solidity
function addOracle(address _a) external
```

*Adds an oracle*

### Parameters

| Name | Type    | Description |
| ---- | ------- | ----------- |
| \_a  | address | new value   |

## replaceOracle

```solidity
function replaceOracle(uint256 _index, address _a) external
```

*Replaces an oracle*

### Parameters

| Name    | Type    | Description  |
| ------- | ------- | ------------ |
| \_index | uint256 | oracle index |
| \_a     | address | new value    |

## removeOracle

```solidity
function removeOracle(uint256 _index) external
```

*Removes an oracle*

### Parameters

| Name    | Type    | Description  |
| ------- | ------- | ------------ |
| \_index | uint256 | oracle index |

## setMarketJobId

```solidity
function setMarketJobId(bytes32 _jobId) external
```

*Updates market job id*

### Parameters

| Name    | Type    | Description |
| ------- | ------- | ----------- |
| \_jobId | bytes32 | new value   |

## setLimitJobId

```solidity
function setLimitJobId(bytes32 _jobId) external
```

*Updates lookback job id*

### Parameters

| Name    | Type    | Description |
| ------- | ------- | ----------- |
| \_jobId | bytes32 | new value   |

## getPrice

```solidity
function getPrice(uint8 _collateralIndex, uint16 _pairIndex, struct ITradingStorage.Id _tradeId, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral, uint256 _fromBlock) external virtual
```

*Requests price from oracles*

### Parameters

| Name                     | Type                                                                                               | Description                                                      |
| ------------------------ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| \_collateralIndex        | uint8                                                                                              | collateral index                                                 |
| \_pairIndex              | uint16                                                                                             | pair index                                                       |
| \_tradeId                | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | trade id                                                         |
| \_orderId                | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id                                                         |
| \_orderType              | enum ITradingStorage.PendingOrderType                                                              | order type                                                       |
| \_positionSizeCollateral | uint256                                                                                            | position size (collateral precision)                             |
| \_fromBlock              | uint256                                                                                            | block number from which to start fetching prices (for lookbacks) |

## fulfill

```solidity
function fulfill(bytes32 _requestId, uint256 _priceData) external
```

*Fulfills price request, called by chainlink oracles*

### Parameters

| Name        | Type    | Description |
| ----------- | ------- | ----------- |
| \_requestId | bytes32 | request id  |
| \_priceData | uint256 | price data  |

## claimBackLink

```solidity
function claimBackLink() external
```

*Claims back LINK tokens, called by gov fund*

## getLinkFee

```solidity
function getLinkFee(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) external view returns (uint256)
```

*Returns LINK fee for price request*

### Parameters

| Name                     | Type    | Description                                               |
| ------------------------ | ------- | --------------------------------------------------------- |
| \_collateralIndex        | uint8   | collateral index                                          |
| \_trader                 | address | trader address                                            |
| \_pairIndex              | uint16  | pair index                                                |
| \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) |

## getCollateralPriceUsd

```solidity
function getCollateralPriceUsd(uint8 _collateralIndex) external view returns (uint256)
```

*Returns collateral/USD price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getUsdNormalizedValue

```solidity
function getUsdNormalizedValue(uint8 _collateralIndex, uint256 _collateralValue) external view returns (uint256)
```

*Returns USD normalized value from collateral value*

### Parameters

| Name              | Type    | Description                             |
| ----------------- | ------- | --------------------------------------- |
| \_collateralIndex | uint8   | index of collateral                     |
| \_collateralValue | uint256 | collateral value (collateral precision) |

## getCollateralFromUsdNormalizedValue

```solidity
function getCollateralFromUsdNormalizedValue(uint8 _collateralIndex, uint256 _normalizedValue) external view returns (uint256)
```

*Returns collateral value (collateral precision) from USD normalized value*

### Parameters

| Name              | Type    | Description                 |
| ----------------- | ------- | --------------------------- |
| \_collateralIndex | uint8   | index of collateral         |
| \_normalizedValue | uint256 | normalized value (1e18 USD) |

## getGnsPriceUsd

```solidity
function getGnsPriceUsd(uint8 _collateralIndex) external view virtual returns (uint256)
```

*Returns GNS/USD price based on GNS/collateral price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getGnsPriceUsd

```solidity
function getGnsPriceUsd(uint8 _collateralIndex, uint256 _gnsPriceCollateral) external view returns (uint256)
```

*Returns GNS/USD price based on GNS/collateral price*

### Parameters

| Name                 | Type    | Description                 |
| -------------------- | ------- | --------------------------- |
| \_collateralIndex    | uint8   | index of collateral         |
| \_gnsPriceCollateral | uint256 | GNS/collateral price (1e10) |

## getGnsPriceCollateralIndex

```solidity
function getGnsPriceCollateralIndex(uint8 _collateralIndex) external view virtual returns (uint256)
```

*Returns GNS/collateral price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getGnsPriceCollateralAddress

```solidity
function getGnsPriceCollateralAddress(address _collateral) external view virtual returns (uint256)
```

*Returns GNS/collateral price*

### Parameters

| Name         | Type    | Description               |
| ------------ | ------- | ------------------------- |
| \_collateral | address | address of the collateral |

## getLinkUsdPriceFeed

```solidity
function getLinkUsdPriceFeed() external view returns (contract IChainlinkFeed)
```

*Returns the link/usd price feed address*

## getTwapInterval

```solidity
function getTwapInterval() external view returns (uint24)
```

*Returns the twap interval in seconds*

## getMinAnswers

```solidity
function getMinAnswers() external view returns (uint8)
```

*Returns the minimum answers to execute an order and take the median*

## getMarketJobId

```solidity
function getMarketJobId() external view returns (bytes32)
```

*Returns the market job id*

## getLimitJobId

```solidity
function getLimitJobId() external view returns (bytes32)
```

*Returns the limit job id*

## getOracle

```solidity
function getOracle(uint256 _index) external view returns (address)
```

*Returns a specific oracle*

### Parameters

| Name    | Type    | Description         |
| ------- | ------- | ------------------- |
| \_index | uint256 | index of the oracle |

## getOracles

```solidity
function getOracles() external view returns (address[])
```

*Returns all oracles*

## getCollateralGnsLiquidityPool

```solidity
function getCollateralGnsLiquidityPool(uint8 _collateralIndex) external view returns (struct IPriceAggregator.LiquidityPoolInfo)
```

*Returns collateral/gns liquidity pool info*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getCollateralUsdPriceFeed

```solidity
function getCollateralUsdPriceFeed(uint8 _collateralIndex) external view returns (contract IChainlinkFeed)
```

*Returns collateral/usd chainlink price feed*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getPriceAggregatorOrder

```solidity
function getPriceAggregatorOrder(bytes32 _requestId) external view returns (struct IPriceAggregator.Order)
```

*Returns order data*

### Parameters

| Name        | Type    | Description         |
| ----------- | ------- | ------------------- |
| \_requestId | bytes32 | index of collateral |

## getPriceAggregatorOrderAnswers

```solidity
function getPriceAggregatorOrderAnswers(struct ITradingStorage.Id _orderId) external view returns (struct IPriceAggregator.OrderAnswer[])
```

*Returns order data*

### Parameters

| Name      | Type                                                                                               | Description |
| --------- | -------------------------------------------------------------------------------------------------- | ----------- |
| \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id    |

## getChainlinkToken

```solidity
function getChainlinkToken() external view returns (address)
```

*Returns chainlink token address*

## getRequestCount

```solidity
function getRequestCount() external view returns (uint256)
```

*Returns requestCount (used by ChainlinkClientUtils)*

## getPendingRequest

```solidity
function getPendingRequest(bytes32 _id) external view returns (address)
```

*Returns pendingRequests mapping entry (used by ChainlinkClientUtils)*


# GNSTradingInteractions

*Facet #7: Trading (user interactions)*

## constructor

```solidity
constructor() public
```

## initializeTrading

```solidity
function initializeTrading(uint16 _marketOrdersTimeoutBlocks, address[] _usersByPassTriggerLink) external
```

*Initializes the trading facet*

### Parameters

| Name                        | Type       | Description                                                             |
| --------------------------- | ---------- | ----------------------------------------------------------------------- |
| \_marketOrdersTimeoutBlocks | uint16     | The number of blocks after which a market order is considered timed out |
| \_usersByPassTriggerLink    | address\[] |                                                                         |

## updateMarketOrdersTimeoutBlocks

```solidity
function updateMarketOrdersTimeoutBlocks(uint16 _valueBlocks) external
```

*Updates marketOrdersTimeoutBlocks*

### Parameters

| Name          | Type   | Description                                 |
| ------------- | ------ | ------------------------------------------- |
| \_valueBlocks | uint16 | blocks after which a market order times out |

## updateByPassTriggerLink

```solidity
function updateByPassTriggerLink(address[] _users, bool[] _shouldByPass) external
```

*Updates the users that can bypass the link cost of triggerOrder*

### Parameters

| Name           | Type       | Description                                                      |
| -------------- | ---------- | ---------------------------------------------------------------- |
| \_users        | address\[] | array of addresses that can bypass the link cost of triggerOrder |
| \_shouldByPass | bool\[]    | whether each user should bypass the link cost                    |

## setTradingDelegate

```solidity
function setTradingDelegate(address _delegate) external
```

\_Sets *delegate as the new delegate of caller (can call delegatedAction)*

### Parameters

| Name       | Type    | Description              |
| ---------- | ------- | ------------------------ |
| \_delegate | address | the new delegate address |

## removeTradingDelegate

```solidity
function removeTradingDelegate() external
```

*Removes the delegate of caller (can't call delegatedAction)*

## delegatedTradingAction

```solidity
function delegatedTradingAction(address _trader, bytes _callData) external returns (bytes)
```

\_Caller executes a trading action on behalf of *trader using delegatecall*

### Parameters

| Name       | Type    | Description                                            |
| ---------- | ------- | ------------------------------------------------------ |
| \_trader   | address | the trader address to execute the trading action for   |
| \_callData | bytes   | the data to be executed (open trade/close trade, etc.) |

## openTrade

```solidity
function openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external
```

*Opens a new trade/limit order/stop order*

### Parameters

| Name           | Type                                                                                                     | Description                                                        |
| -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| \_trade        | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened                                             |
| \_maxSlippageP | uint16                                                                                                   | the maximum allowed slippage % when open the trade (1e3 precision) |
| \_referrer     | address                                                                                                  | the address of the referrer (can only be set once for a trader)    |

## openTradeNative

```solidity
function openTradeNative(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external payable
```

*Wraps native token and opens a new trade/limit order/stop order*

### Parameters

| Name           | Type                                                                                                     | Description                                                        |
| -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| \_trade        | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade) | the trade to be opened                                             |
| \_maxSlippageP | uint16                                                                                                   | the maximum allowed slippage % when open the trade (1e3 precision) |
| \_referrer     | address                                                                                                  | the address of the referrer (can only be set once for a trader)    |

## updateMaxClosingSlippageP

```solidity
function updateMaxClosingSlippageP(uint32 _index, uint16 _maxSlippageP) external
```

*Updates existing trade's max closing slippage % for caller*

### Parameters

| Name           | Type   | Description                                |
| -------------- | ------ | ------------------------------------------ |
| \_index        | uint32 | index of trade                             |
| \_maxSlippageP | uint16 | new max closing slippage % (1e3 precision) |

## closeTradeMarket

```solidity
function closeTradeMarket(uint32 _index, uint64 _expectedPrice) external
```

*Closes an open trade (market order) for caller*

### Parameters

| Name            | Type   | Description                                                         |
| --------------- | ------ | ------------------------------------------------------------------- |
| \_index         | uint32 | the index of the trade of caller                                    |
| \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) |

## updateOpenOrder

```solidity
function updateOpenOrder(uint32 _index, uint64 _triggerPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external
```

*Updates an existing limit/stop order for caller*

### Parameters

| Name           | Type   | Description                                            |
| -------------- | ------ | ------------------------------------------------------ |
| \_index        | uint32 | index of limit/stop order of caller                    |
| \_triggerPrice | uint64 | new trigger price of limit/stop order (1e10 precision) |
| \_tp           | uint64 | new tp of limit/stop order (1e10 precision)            |
| \_sl           | uint64 | new sl of limit/stop order (1e10 precision)            |
| \_maxSlippageP | uint16 | new max slippage % of limit/stop order (1e3 precision) |

## cancelOpenOrder

```solidity
function cancelOpenOrder(uint32 _index) external
```

*Cancels an open limit/stop order for caller*

### Parameters

| Name    | Type   | Description                         |
| ------- | ------ | ----------------------------------- |
| \_index | uint32 | index of limit/stop order of caller |

## updateTp

```solidity
function updateTp(uint32 _index, uint64 _newTp) external
```

*Updates the tp of an open trade for caller*

### Parameters

| Name    | Type   | Description                           |
| ------- | ------ | ------------------------------------- |
| \_index | uint32 | index of open trade of caller         |
| \_newTp | uint64 | new tp of open trade (1e10 precision) |

## updateSl

```solidity
function updateSl(uint32 _index, uint64 _newSl) external
```

*Updates the sl of an open trade for caller*

### Parameters

| Name    | Type   | Description                           |
| ------- | ------ | ------------------------------------- |
| \_index | uint32 | index of open trade of caller         |
| \_newSl | uint64 | new sl of open trade (1e10 precision) |

## updateLeverage

```solidity
function updateLeverage(uint32 _index, uint24 _newLeverage) external
```

*Update trade leverage*

### Parameters

| Name          | Type   | Description        |
| ------------- | ------ | ------------------ |
| \_index       | uint32 | index of trade     |
| \_newLeverage | uint24 | new leverage (1e3) |

## increasePositionSize

```solidity
function increasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice, uint16 _maxSlippageP) external
```

*Increase trade position size*

### Parameters

| Name              | Type    | Description                                  |
| ----------------- | ------- | -------------------------------------------- |
| \_index           | uint32  | index of trade                               |
| \_collateralDelta | uint120 | collateral to add (collateral precision)     |
| \_leverageDelta   | uint24  | partial trade leverage (1e3)                 |
| \_expectedPrice   | uint64  | expected price of execution (1e10 precision) |
| \_maxSlippageP    | uint16  | max slippage % (1e3)                         |

## decreasePositionSize

```solidity
function decreasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice) external
```

*Decrease trade position size*

### Parameters

| Name              | Type    | Description                                                         |
| ----------------- | ------- | ------------------------------------------------------------------- |
| \_index           | uint32  | index of trade                                                      |
| \_collateralDelta | uint120 | collateral to remove (collateral precision)                         |
| \_leverageDelta   | uint24  | leverage to reduce by (1e3)                                         |
| \_expectedPrice   | uint64  | expected closing price, used to check max slippage (1e10 precision) |

## triggerOrder

```solidity
function triggerOrder(uint256 _packed) external
```

*Initiates a new trigger order (for tp/sl/liq/limit/stop orders)*

### Parameters

| Name     | Type    | Description                                                     |
| -------- | ------- | --------------------------------------------------------------- |
| \_packed | uint256 | the packed data of the trigger order (orderType, trader, index) |

## cancelOrderAfterTimeout

```solidity
function cancelOrderAfterTimeout(uint32 _orderIndex) external
```

*Safety function in case oracles don't answer in time, allows caller to cancel a pending order and if relevant claim back any stuck collateral Only allowed for MARKET\_OPEN, MARKET\_CLOSE, UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE orders*

### Parameters

| Name         | Type   | Description                           |
| ------------ | ------ | ------------------------------------- |
| \_orderIndex | uint32 | the id of the pending order to cancel |

## getWrappedNativeToken

```solidity
function getWrappedNativeToken() external view returns (address)
```

*Returns the wrapped native token or address(0) if the current chain, or the wrapped token, is not supported.*

## isWrappedNativeToken

```solidity
function isWrappedNativeToken(address _token) external view returns (bool)
```

*Returns true if the token is the wrapped native token for the current chain, where supported.*

### Parameters

| Name    | Type    | Description   |
| ------- | ------- | ------------- |
| \_token | address | token address |

## getTradingDelegate

```solidity
function getTradingDelegate(address _trader) external view returns (address)
```

*Returns the address a trader delegates his trading actions to*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_trader | address | address of the trader |

## getMarketOrdersTimeoutBlocks

```solidity
function getMarketOrdersTimeoutBlocks() external view returns (uint16)
```

*Returns the current marketOrdersTimeoutBlocks value*

## getByPassTriggerLink

```solidity
function getByPassTriggerLink(address _user) external view returns (bool)
```

*Returns whether a user bypasses trigger link costs*

### Parameters

| Name   | Type    | Description         |
| ------ | ------- | ------------------- |
| \_user | address | address of the user |


# GNSTriggerRewards

*Facet #6: Trigger rewards*

## constructor

```solidity
constructor() public
```

## initializeTriggerRewards

```solidity
function initializeTriggerRewards(uint16 _timeoutBlocks) external
```

*Initializes parameters for trigger rewards facet*

### Parameters

| Name            | Type   | Description                            |
| --------------- | ------ | -------------------------------------- |
| \_timeoutBlocks | uint16 | blocks after which a trigger times out |

## updateTriggerTimeoutBlocks

```solidity
function updateTriggerTimeoutBlocks(uint16 _timeoutBlocks) external
```

*Updates the blocks after which a trigger times out*

### Parameters

| Name            | Type   | Description                            |
| --------------- | ------ | -------------------------------------- |
| \_timeoutBlocks | uint16 | blocks after which a trigger times out |

## distributeTriggerReward

```solidity
function distributeTriggerReward(uint256 _rewardGns) external virtual
```

*Distributes GNS rewards to oracles for a specific trigger*

### Parameters

| Name        | Type    | Description                                      |
| ----------- | ------- | ------------------------------------------------ |
| \_rewardGns | uint256 | total GNS reward to be distributed among oracles |

## claimPendingTriggerRewards

```solidity
function claimPendingTriggerRewards(address _oracle) external
```

*Claims pending GNS trigger rewards for the caller*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_oracle | address | address of the oracle |

## getTriggerTimeoutBlocks

```solidity
function getTriggerTimeoutBlocks() external view returns (uint16)
```

*Returns current triggerTimeoutBlocks value*

## hasActiveOrder

```solidity
function hasActiveOrder(uint256 _orderBlock) external view returns (bool)
```

*Checks if an order is active (exists and has not timed out)*

### Parameters

| Name         | Type    | Description               |
| ------------ | ------- | ------------------------- |
| \_orderBlock | uint256 | block number of the order |

## getTriggerPendingRewardsGns

```solidity
function getTriggerPendingRewardsGns(address _oracle) external view returns (uint256)
```

*Returns the pending GNS trigger rewards for an oracle*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_oracle | address | address of the oracle |


# GNSFeeTiers

*Facet #3: Fee tiers*

## constructor

```solidity
constructor() public
```

## initializeFeeTiers

```solidity
function initializeFeeTiers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers, uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external
```

### Parameters

| Name                     | Type                                                                                                 | Description                                                     |
| ------------------------ | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| \_groupIndices           | uint256\[]                                                                                           | group indices (pairs storage fee index) to initialize           |
| \_groupVolumeMultipliers | uint256\[]                                                                                           | corresponding group volume multipliers (1e3)                    |
| \_feeTiersIndices        | uint256\[]                                                                                           | fee tiers indices to initialize                                 |
| \_feeTiers               | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | fee tiers values to initialize (feeMultiplier, pointsThreshold) |

## setGroupVolumeMultipliers

```solidity
function setGroupVolumeMultipliers(uint256[] _groupIndices, uint256[] _groupVolumeMultipliers) external
```

*Updates groups volume multipliers*

### Parameters

| Name                     | Type       | Description                                |
| ------------------------ | ---------- | ------------------------------------------ |
| \_groupIndices           | uint256\[] | indices of groups to update                |
| \_groupVolumeMultipliers | uint256\[] | corresponding new volume multipliers (1e3) |

## setFeeTiers

```solidity
function setFeeTiers(uint256[] _feeTiersIndices, struct IFeeTiers.FeeTier[] _feeTiers) external
```

*Updates fee tiers*

### Parameters

| Name              | Type                                                                                                 | Description                                           |
| ----------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| \_feeTiersIndices | uint256\[]                                                                                           | indices of fee tiers to update                        |
| \_feeTiers        | [IFeeTiers.FeeTier\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#feetier) | new fee tiers values (feeMultiplier, pointsThreshold) |

## setTradersFeeTiersEnrollment

```solidity
function setTradersFeeTiersEnrollment(address[] _traders, struct IFeeTiers.TraderEnrollment[] _values) external
```

*Updates traders enrollment status in fee tiers*

### Parameters

| Name      | Type                                                                                                                   | Description                     |
| --------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| \_traders | address\[]                                                                                                             | group of traders                |
| \_values  | [IFeeTiers.TraderEnrollment\[\]](/developer/technical-reference/contracts/interfaces/types/ifeetiers#traderenrollment) | corresponding enrollment values |

## addTradersUnclaimedPoints

```solidity
function addTradersUnclaimedPoints(address[] _traders, enum IFeeTiers.CreditType[] _creditTypes, uint224[] _points) external
```

*Credits points to traders*

### Parameters

| Name          | Type                         | Description                            |
| ------------- | ---------------------------- | -------------------------------------- |
| \_traders     | address\[]                   | traders addresses                      |
| \_creditTypes | enum IFeeTiers.CreditType\[] | types of credit (IMMEDIATE, CLAIMABLE) |
| \_points      | uint224\[]                   | points to credit (1e18)                |

## updateTraderPoints

```solidity
function updateTraderPoints(address _trader, uint256 _volumeUsd, uint256 _pairIndex) external virtual
```

*Increases daily points from a new trade, re-calculate trailing points, and cache daily fee tier for a trader.*

### Parameters

| Name        | Type    | Description                  |
| ----------- | ------- | ---------------------------- |
| \_trader    | address | trader address               |
| \_volumeUsd | uint256 | trading volume in USD (1e18) |
| \_pairIndex | uint256 | pair index                   |

## calculateFeeAmount

```solidity
function calculateFeeAmount(address _trader, uint256 _normalFeeAmountCollateral) external view returns (uint256)
```

*Returns fee amount after applying the trader's active fee tier multiplier*

### Parameters

| Name                        | Type    | Description                            |
| --------------------------- | ------- | -------------------------------------- |
| \_trader                    | address | address of trader                      |
| \_normalFeeAmountCollateral | uint256 | base fee amount (collateral precision) |

## getFeeTiersCount

```solidity
function getFeeTiersCount() external view returns (uint256)
```

Returns the current number of active fee tiers

## getFeeTier

```solidity
function getFeeTier(uint256 _feeTierIndex) external view returns (struct IFeeTiers.FeeTier)
```

*Returns a fee tier's details (feeMultiplier, pointsThreshold)*

### Parameters

| Name           | Type    | Description    |
| -------------- | ------- | -------------- |
| \_feeTierIndex | uint256 | fee tier index |

## getGroupVolumeMultiplier

```solidity
function getGroupVolumeMultiplier(uint256 _groupIndex) external view returns (uint256)
```

*Returns a group's volume multiplier*

### Parameters

| Name         | Type    | Description                           |
| ------------ | ------- | ------------------------------------- |
| \_groupIndex | uint256 | group index (pairs storage fee index) |

## getFeeTiersTraderInfo

```solidity
function getFeeTiersTraderInfo(address _trader) external view returns (struct IFeeTiers.TraderInfo)
```

*Returns a trader's info (lastDayUpdated, trailingPoints)*

### Parameters

| Name     | Type    | Description    |
| -------- | ------- | -------------- |
| \_trader | address | trader address |

## getFeeTiersTraderDailyInfo

```solidity
function getFeeTiersTraderDailyInfo(address _trader, uint32 _day) external view returns (struct IFeeTiers.TraderDailyInfo)
```

*Returns a trader's daily fee tier info (feeMultiplierCache, points)*

### Parameters

| Name     | Type    | Description    |
| -------- | ------- | -------------- |
| \_trader | address | trader address |
| \_day    | uint32  | day            |

## getTraderFeeTiersEnrollment

```solidity
function getTraderFeeTiersEnrollment(address _trader) external view returns (struct IFeeTiers.TraderEnrollment)
```

*Returns a trader's fee tiers enrollment status*

### Parameters

| Name     | Type    | Description    |
| -------- | ------- | -------------- |
| \_trader | address | trader address |

## getTraderUnclaimedPoints

```solidity
function getTraderUnclaimedPoints(address _trader) external view returns (uint224)
```

*Returns a trader's unclaimed points, credited by Governance*

### Parameters

| Name     | Type    | Description    |
| -------- | ------- | -------------- |
| \_trader | address | trader address |


# GNSPairsStorage

*Facet #1: Pairs storage*

## constructor

```solidity
constructor() public
```

## initializeGroupLiquidationParams

```solidity
function initializeGroupLiquidationParams(struct IPairsStorage.GroupLiquidationParams[] _groupLiquidationParams) external
```

*Initializes liquidation params for all existing groups*

### Parameters

| Name                     | Type                                                                                                                                       | Description                                                          |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
| \_groupLiquidationParams | [IPairsStorage.GroupLiquidationParams\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | liquidation params for each group (index corresponds to group index) |

## initializeNewFees

```solidity
function initializeNewFees(struct IPairsStorage.GlobalTradeFeeParams _tradeFeeParams) external
```

*Copies all existing fee groups to new mapping, multiplies existing groups min/max lev by 1e3, initializes new global trade fee params*

### Parameters

| Name             | Type                                                                                                                               | Description             |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_tradeFeeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | global trade fee params |

## addPairs

```solidity
function addPairs(struct IPairsStorage.Pair[] _pairs) external
```

*Adds new trading pairs*

### Parameters

| Name    | Type                                                                                                   | Description  |
| ------- | ------------------------------------------------------------------------------------------------------ | ------------ |
| \_pairs | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | pairs to add |

## updatePairs

```solidity
function updatePairs(uint256[] _pairIndices, struct IPairsStorage.Pair[] _pairs) external
```

*Updates trading pairs*

### Parameters

| Name          | Type                                                                                                   | Description      |
| ------------- | ------------------------------------------------------------------------------------------------------ | ---------------- |
| \_pairIndices | uint256\[]                                                                                             | indices of pairs |
| \_pairs       | [IPairsStorage.Pair\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#pair) | new pairs values |

## addGroups

```solidity
function addGroups(struct IPairsStorage.Group[] _groups) external
```

*Adds new pair groups*

### Parameters

| Name     | Type                                                                                                     | Description   |
| -------- | -------------------------------------------------------------------------------------------------------- | ------------- |
| \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | groups to add |

## updateGroups

```solidity
function updateGroups(uint256[] _ids, struct IPairsStorage.Group[] _groups) external
```

*Updates pair groups*

### Parameters

| Name     | Type                                                                                                     | Description       |
| -------- | -------------------------------------------------------------------------------------------------------- | ----------------- |
| \_ids    | uint256\[]                                                                                               | indices of groups |
| \_groups | [IPairsStorage.Group\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#group) | new groups values |

## addFees

```solidity
function addFees(struct IPairsStorage.FeeGroup[] _fees) external
```

*Adds new pair fees groups*

### Parameters

| Name   | Type                                                                                                           | Description |
| ------ | -------------------------------------------------------------------------------------------------------------- | ----------- |
| \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | fees to add |

## updateFees

```solidity
function updateFees(uint256[] _ids, struct IPairsStorage.FeeGroup[] _fees) external
```

*Updates pair fees groups*

### Parameters

| Name   | Type                                                                                                           | Description     |
| ------ | -------------------------------------------------------------------------------------------------------------- | --------------- |
| \_ids  | uint256\[]                                                                                                     | indices of fees |
| \_fees | [IPairsStorage.FeeGroup\[\]](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#feegroup) | new fees values |

## setGroupLiquidationParams

```solidity
function setGroupLiquidationParams(uint256 _groupIndex, struct IPairsStorage.GroupLiquidationParams _params) external
```

*Updates group liquidation params (will only apply for trades opened after the change)*

### Parameters

| Name         | Type                                                                                                                                   | Description            |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| \_groupIndex | uint256                                                                                                                                | index of group         |
| \_params     | [IPairsStorage.GroupLiquidationParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#groupliquidationparams) | new liquidation params |

## setGlobalTradeFeeParams

```solidity
function setGlobalTradeFeeParams(struct IPairsStorage.GlobalTradeFeeParams _feeParams) external
```

*Updates global trade fee params*

### Parameters

| Name        | Type                                                                                                                               | Description    |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| \_feeParams | [IPairsStorage.GlobalTradeFeeParams](/developer/technical-reference/contracts/interfaces/types/ipairsstorage#globaltradefeeparams) | new fee params |

## setPairCustomMaxLeverages

```solidity
function setPairCustomMaxLeverages(uint256[] _indices, uint256[] _values) external
```

*Updates pair custom max leverages (if unset group default is used); useful to delist a pair if new value is below the pair's group minLeverage*

### Parameters

| Name      | Type       | Description                              |
| --------- | ---------- | ---------------------------------------- |
| \_indices | uint256\[] | indices of pairs                         |
| \_values  | uint256\[] | new custom max leverages (1e3 precision) |

## pairJob

```solidity
function pairJob(uint256 _pairIndex) external view returns (string, string)
```

*Returns data needed by price aggregator when doing a new price request*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

### Return Values

| Name | Type   | Description |
| ---- | ------ | ----------- |
| \[0] | string |             |
| \[1] | string |             |

## isPairListed

```solidity
function isPairListed(string _from, string _to) external view returns (bool)
```

*Returns whether a pair is listed*

### Parameters

| Name   | Type   | Description         |
| ------ | ------ | ------------------- |
| \_from | string | pair from (eg. BTC) |
| \_to   | string | pair to (eg. USD)   |

## isPairIndexListed

```solidity
function isPairIndexListed(uint256 _pairIndex) external view returns (bool)
```

*Returns whether a pair index is listed*

### Parameters

| Name        | Type    | Description            |
| ----------- | ------- | ---------------------- |
| \_pairIndex | uint256 | index of pair to check |

## pairs

```solidity
function pairs(uint256 _index) external view returns (struct IPairsStorage.Pair)
```

*Returns a pair's details*

### Parameters

| Name    | Type    | Description   |
| ------- | ------- | ------------- |
| \_index | uint256 | index of pair |

## pairsCount

```solidity
function pairsCount() external view returns (uint256)
```

*Returns number of listed pairs*

## pairSpreadP

```solidity
function pairSpreadP(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's spread % (1e10 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairMinLeverage

```solidity
function pairMinLeverage(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's min leverage (1e3 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairTotalPositionSizeFeeP

```solidity
function pairTotalPositionSizeFeeP(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's total position size fee % (1e10 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairTotalLiqCollateralFeeP

```solidity
function pairTotalLiqCollateralFeeP(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's total liquidation collateral fee % (1e10 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairOraclePositionSizeFeeP

```solidity
function pairOraclePositionSizeFeeP(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's oracle position size fee % (1e10 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairMinPositionSizeUsd

```solidity
function pairMinPositionSizeUsd(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's min position size in USD (1e18 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## getGlobalTradeFeeParams

```solidity
function getGlobalTradeFeeParams() external view returns (struct IPairsStorage.GlobalTradeFeeParams)
```

*Returns global trade fee params*

## pairMinFeeUsd

```solidity
function pairMinFeeUsd(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's minimum trading fee in USD (1e18 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## groups

```solidity
function groups(uint256 _index) external view returns (struct IPairsStorage.Group)
```

*Returns a group details*

### Parameters

| Name    | Type    | Description    |
| ------- | ------- | -------------- |
| \_index | uint256 | index of group |

## groupsCount

```solidity
function groupsCount() external view returns (uint256)
```

*Returns number of listed groups*

## fees

```solidity
function fees(uint256 _index) external view returns (struct IPairsStorage.FeeGroup)
```

*Returns a fee group details*

### Parameters

| Name    | Type    | Description        |
| ------- | ------- | ------------------ |
| \_index | uint256 | index of fee group |

## feesCount

```solidity
function feesCount() external view returns (uint256)
```

*Returns number of listed fee groups*

## pairMaxLeverage

```solidity
function pairMaxLeverage(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's active max leverage; custom if set, otherwise group default (1e3 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## pairCustomMaxLeverage

```solidity
function pairCustomMaxLeverage(uint256 _pairIndex) external view returns (uint256)
```

*Returns a pair's custom max leverage; 0 if not set (1e3 precision)*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## getAllPairsRestrictedMaxLeverage

```solidity
function getAllPairsRestrictedMaxLeverage() external view returns (uint256[])
```

*Returns all listed pairs custom max leverages (1e3 precision)*

## getGroupLiquidationParams

```solidity
function getGroupLiquidationParams(uint256 _groupIndex) external view returns (struct IPairsStorage.GroupLiquidationParams)
```

*Returns a group's liquidation params*

## getPairLiquidationParams

```solidity
function getPairLiquidationParams(uint256 _pairIndex) external view returns (struct IPairsStorage.GroupLiquidationParams)
```

*Returns a pair's group liquidation params*


# GNSPriceImpact

*Facet #4: Price impact OI windows*

## constructor

```solidity
constructor() public
```

## initializePriceImpact

```solidity
function initializePriceImpact(uint48 _windowsDuration, uint48 _windowsCount) external
```

*Initializes price impact facet*

### Parameters

| Name              | Type   | Description                |
| ----------------- | ------ | -------------------------- |
| \_windowsDuration | uint48 | windows duration (seconds) |
| \_windowsCount    | uint48 | windows count              |

## initializeNegPnlCumulVolMultiplier

```solidity
function initializeNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external
```

*Initializes negative pnl cumulative volume multiplier*

### Parameters

| Name                       | Type   | Description      |
| -------------------------- | ------ | ---------------- |
| \_negPnlCumulVolMultiplier | uint40 | new value (1e10) |

## initializePairFactors

```solidity
function initializePairFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors, uint32[] _protectionCloseFactorBlocks, uint40[] _cumulativeFactors) external
```

*Initializes pair factors*

### Parameters

| Name                          | Type      | Description                     |
| ----------------------------- | --------- | ------------------------------- |
| \_pairIndices                 | uint16\[] | pair indices to initialize      |
| \_protectionCloseFactors      | uint40\[] | protection close factors (1e10) |
| \_protectionCloseFactorBlocks | uint32\[] | protection close factor blocks  |
| \_cumulativeFactors           | uint40\[] | cumulative factors (1e10)       |

## setPriceImpactWindowsCount

```solidity
function setPriceImpactWindowsCount(uint48 _newWindowsCount) external
```

*Updates price impact windows count*

### Parameters

| Name              | Type   | Description       |
| ----------------- | ------ | ----------------- |
| \_newWindowsCount | uint48 | new windows count |

## setPriceImpactWindowsDuration

```solidity
function setPriceImpactWindowsDuration(uint48 _newWindowsDuration) external
```

*Updates price impact windows duration*

### Parameters

| Name                 | Type   | Description                    |
| -------------------- | ------ | ------------------------------ |
| \_newWindowsDuration | uint48 | new windows duration (seconds) |

## setNegPnlCumulVolMultiplier

```solidity
function setNegPnlCumulVolMultiplier(uint40 _negPnlCumulVolMultiplier) external
```

*Updates negative pnl cumulative volume multiplier*

### Parameters

| Name                       | Type   | Description      |
| -------------------------- | ------ | ---------------- |
| \_negPnlCumulVolMultiplier | uint40 | new value (1e10) |

## setProtectionCloseFactorWhitelist

```solidity
function setProtectionCloseFactorWhitelist(address[] _traders, bool[] _whitelisted) external
```

*Whitelists/unwhitelists traders from protection close factor*

### Parameters

| Name          | Type       | Description       |
| ------------- | ---------- | ----------------- |
| \_traders     | address\[] | traders addresses |
| \_whitelisted | bool\[]    | values            |

## setPairDepths

```solidity
function setPairDepths(uint256[] _indices, uint128[] _depthsAboveUsd, uint128[] _depthsBelowUsd) external
```

*Updates pairs 1% depths above and below*

### Parameters

| Name             | Type       | Description                   |
| ---------------- | ---------- | ----------------------------- |
| \_indices        | uint256\[] | indices of pairs              |
| \_depthsAboveUsd | uint128\[] | depths above the price in USD |
| \_depthsBelowUsd | uint128\[] | depths below the price in USD |

## setProtectionCloseFactors

```solidity
function setProtectionCloseFactors(uint16[] _pairIndices, uint40[] _protectionCloseFactors) external
```

*Sets protection close factors for pairs*

### Parameters

| Name                     | Type      | Description                         |
| ------------------------ | --------- | ----------------------------------- |
| \_pairIndices            | uint16\[] | pair indices to update              |
| \_protectionCloseFactors | uint40\[] | new protection close factors (1e10) |

## setProtectionCloseFactorBlocks

```solidity
function setProtectionCloseFactorBlocks(uint16[] _pairIndices, uint32[] _protectionCloseFactorBlocks) external
```

*Sets protection close factor blocks duration for pairs*

### Parameters

| Name                          | Type      | Description                        |
| ----------------------------- | --------- | ---------------------------------- |
| \_pairIndices                 | uint16\[] | pair indices to update             |
| \_protectionCloseFactorBlocks | uint32\[] | new protection close factor blocks |

## setCumulativeFactors

```solidity
function setCumulativeFactors(uint16[] _pairIndices, uint40[] _cumulativeFactors) external
```

*Sets cumulative factors for pairs*

### Parameters

| Name                | Type      | Description                   |
| ------------------- | --------- | ----------------------------- |
| \_pairIndices       | uint16\[] | pair indices to update        |
| \_cumulativeFactors | uint40\[] | new cumulative factors (1e10) |

## setExemptOnOpen

```solidity
function setExemptOnOpen(uint16[] _pairIndices, bool[] _exemptOnOpen) external
```

*Sets whether pairs are exempt from price impact on open*

### Parameters

| Name           | Type      | Description            |
| -------------- | --------- | ---------------------- |
| \_pairIndices  | uint16\[] | pair indices to update |
| \_exemptOnOpen | bool\[]   | new values             |

## setExemptAfterProtectionCloseFactor

```solidity
function setExemptAfterProtectionCloseFactor(uint16[] _pairIndices, bool[] _exemptAfterProtectionCloseFactor) external
```

*Sets whether pairs are exempt from price impact on close once protection close factor has expired*

### Parameters

| Name                               | Type      | Description            |
| ---------------------------------- | --------- | ---------------------- |
| \_pairIndices                      | uint16\[] | pair indices to update |
| \_exemptAfterProtectionCloseFactor | bool\[]   | new values             |

## addPriceImpactOpenInterest

```solidity
function addPriceImpactOpenInterest(address _trader, uint32 _index, uint256 _oiDeltaCollateral, bool _open, bool _isPnlPositive) external virtual
```

*Adds open interest to current window*

### Parameters

| Name                | Type    | Description                                                                        |
| ------------------- | ------- | ---------------------------------------------------------------------------------- |
| \_trader            | address | trader address                                                                     |
| \_index             | uint32  | trade index                                                                        |
| \_oiDeltaCollateral | uint256 | open interest to add (collateral precision)                                        |
| \_open              | bool    | whether it corresponds to opening or closing a trade                               |
| \_isPnlPositive     | bool    | whether it corresponds to a positive pnl trade (only relevant when \_open = false) |

## getPriceImpactOi

```solidity
function getPriceImpactOi(uint256 _pairIndex, bool _long) external view returns (uint256 activeOi)
```

*Returns active open interest used in price impact calculation for a pair and side (long/short)*

### Parameters

| Name        | Type    | Description                    |
| ----------- | ------- | ------------------------------ |
| \_pairIndex | uint256 | index of pair                  |
| \_long      | bool    | true for long, false for short |

## getTradePriceImpact

```solidity
function getTradePriceImpact(address _trader, uint256 _marketPrice, uint256 _pairIndex, bool _long, uint256 _tradeOpenInterestUsd, bool _isPnlPositive, bool _open, uint256 _lastPosIncreaseBlock, enum ITradingStorage.ContractsVersion _contractsVersion) external view returns (uint256 priceImpactP, uint256 priceAfterImpact)
```

*Returns price impact % (1e10 precision) and price after impact (1e10 precision) for a trade*

### Parameters

| Name                   | Type                                  | Description                                                                           |
| ---------------------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| \_trader               | address                               | trader address (to check if whitelisted from protection close factor)                 |
| \_marketPrice          | uint256                               | market price (1e10 precision)                                                         |
| \_pairIndex            | uint256                               | index of pair                                                                         |
| \_long                 | bool                                  | true for long, false for short                                                        |
| \_tradeOpenInterestUsd | uint256                               | open interest of trade in USD (1e18 precision)                                        |
| \_isPnlPositive        | bool                                  | true if positive pnl, false if negative pnl (only relevant when \_open = false)       |
| \_open                 | bool                                  | true on open, false on close                                                          |
| \_lastPosIncreaseBlock | uint256                               | block when trade position size was last increased (only relevant when \_open = false) |
| \_contractsVersion     | enum ITradingStorage.ContractsVersion | trade contracts version                                                               |

## getPairDepth

```solidity
function getPairDepth(uint256 _pairIndex) external view returns (struct IPriceImpact.PairDepth)
```

*Returns a pair's depths above and below the price*

### Parameters

| Name        | Type    | Description   |
| ----------- | ------- | ------------- |
| \_pairIndex | uint256 | index of pair |

## getOiWindowsSettings

```solidity
function getOiWindowsSettings() external view returns (struct IPriceImpact.OiWindowsSettings)
```

*Returns current price impact windows settings*

## getOiWindow

```solidity
function getOiWindow(uint48 _windowsDuration, uint256 _pairIndex, uint256 _windowId) external view returns (struct IPriceImpact.PairOi)
```

*Returns OI window details (long/short OI)*

### Parameters

| Name              | Type    | Description                |
| ----------------- | ------- | -------------------------- |
| \_windowsDuration | uint48  | windows duration (seconds) |
| \_pairIndex       | uint256 | index of pair              |
| \_windowId        | uint256 | id of window               |

## getOiWindows

```solidity
function getOiWindows(uint48 _windowsDuration, uint256 _pairIndex, uint256[] _windowIds) external view returns (struct IPriceImpact.PairOi[])
```

*Returns multiple OI windows details (long/short OI)*

### Parameters

| Name              | Type       | Description                |
| ----------------- | ---------- | -------------------------- |
| \_windowsDuration | uint48     | windows duration (seconds) |
| \_pairIndex       | uint256    | index of pair              |
| \_windowIds       | uint256\[] | ids of windows             |

## getPairDepths

```solidity
function getPairDepths(uint256[] _indices) external view returns (struct IPriceImpact.PairDepth[])
```

*Returns depths above and below the price for multiple pairs*

### Parameters

| Name      | Type       | Description      |
| --------- | ---------- | ---------------- |
| \_indices | uint256\[] | indices of pairs |

## getPairFactors

```solidity
function getPairFactors(uint256[] _indices) external view returns (struct IPriceImpact.PairFactors[])
```

*Returns factors for a set of pairs (1e10)*

### Parameters

| Name      | Type       | Description      |
| --------- | ---------- | ---------------- |
| \_indices | uint256\[] | indices of pairs |

## getNegPnlCumulVolMultiplier

```solidity
function getNegPnlCumulVolMultiplier() external view returns (uint48)
```

*Returns negative pnl cumulative volume multiplier*

## getProtectionCloseFactorWhitelist

```solidity
function getProtectionCloseFactorWhitelist(address _trader) external view returns (bool)
```

*Returns whether a trader is whitelisted from protection close factor*


# GNSReferrals

*Facet #2: Referral system*

## constructor

```solidity
constructor() public
```

## initializeReferrals

```solidity
function initializeReferrals(uint256 _allyFeeP, uint256 _startReferrerFeeP, uint256 _targetVolumeUsd) external
```

### Parameters

| Name                | Type    | Description                                                      |
| ------------------- | ------- | ---------------------------------------------------------------- |
| \_allyFeeP          | uint256 | % of total referral fee going to ally                            |
| \_startReferrerFeeP | uint256 | initial % of total referral fee earned when zero volume referred |
| \_targetVolumeUsd   | uint256 | usd opening volume to refer to reach 100% of referral fee        |

## updateAllyFeeP

```solidity
function updateAllyFeeP(uint256 _value) external
```

*Updates allyFeeP*

### Parameters

| Name    | Type    | Description    |
| ------- | ------- | -------------- |
| \_value | uint256 | new ally fee % |

## updateStartReferrerFeeP

```solidity
function updateStartReferrerFeeP(uint256 _value) external
```

*Updates startReferrerFeeP*

### Parameters

| Name    | Type    | Description              |
| ------- | ------- | ------------------------ |
| \_value | uint256 | new start referrer fee % |

## updateReferralsTargetVolumeUsd

```solidity
function updateReferralsTargetVolumeUsd(uint256 _value) external
```

*Updates targetVolumeUsd*

### Parameters

| Name    | Type    | Description              |
| ------- | ------- | ------------------------ |
| \_value | uint256 | new target volume in usd |

## whitelistAllies

```solidity
function whitelistAllies(address[] _allies) external
```

*Whitelists ally addresses*

### Parameters

| Name     | Type       | Description             |
| -------- | ---------- | ----------------------- |
| \_allies | address\[] | array of ally addresses |

## unwhitelistAllies

```solidity
function unwhitelistAllies(address[] _allies) external
```

*Unwhitelists ally addresses*

### Parameters

| Name     | Type       | Description             |
| -------- | ---------- | ----------------------- |
| \_allies | address\[] | array of ally addresses |

## whitelistReferrers

```solidity
function whitelistReferrers(address[] _referrers, address[] _allies) external
```

*Whitelists referrer addresses*

### Parameters

| Name        | Type       | Description                           |
| ----------- | ---------- | ------------------------------------- |
| \_referrers | address\[] | array of referrer addresses           |
| \_allies    | address\[] | array of corresponding ally addresses |

## unwhitelistReferrers

```solidity
function unwhitelistReferrers(address[] _referrers) external
```

*Unwhitelists referrer addresses*

### Parameters

| Name        | Type       | Description                 |
| ----------- | ---------- | --------------------------- |
| \_referrers | address\[] | array of referrer addresses |

## registerPotentialReferrer

```solidity
function registerPotentialReferrer(address _trader, address _referrer) external virtual
```

*Registers potential referrer for trader (only works if trader wasn't referred yet by someone else)*

### Parameters

| Name       | Type    | Description    |
| ---------- | ------- | -------------- |
| \_trader   | address | trader address |
| \_referrer | address |                |

## distributeReferralReward

```solidity
function distributeReferralReward(address _trader, uint256 _volumeUsd, uint256 _referrerFeeUsd, uint256 _gnsPriceUsd) external virtual
```

*Distributes ally and referrer rewards*

### Parameters

| Name             | Type    | Description                            |
| ---------------- | ------- | -------------------------------------- |
| \_trader         | address | trader address                         |
| \_volumeUsd      | uint256 | trading volume in usd (1e18 precision) |
| \_referrerFeeUsd | uint256 | referrer fee in USD (1e18 precision)   |
| \_gnsPriceUsd    | uint256 | token price in usd (1e10 precision)    |

## claimAllyRewards

```solidity
function claimAllyRewards() external
```

*Claims pending GNS ally rewards of caller*

## claimReferrerRewards

```solidity
function claimReferrerRewards() external
```

*Claims pending GNS referrer rewards of caller*

## getReferrerFeeProgressP

```solidity
function getReferrerFeeProgressP(address _referrer) external view returns (uint256)
```

*Returns referrer fee % progress towards earning 100% based on his volume referred (1e10)*

### Parameters

| Name       | Type    | Description      |
| ---------- | ------- | ---------------- |
| \_referrer | address | referrer address |

## getTraderLastReferrer

```solidity
function getTraderLastReferrer(address _trader) external view returns (address)
```

*Returns last referrer of trader (whether referrer active or not)*

### Parameters

| Name     | Type    | Description       |
| -------- | ------- | ----------------- |
| \_trader | address | address of trader |

## getTraderActiveReferrer

```solidity
function getTraderActiveReferrer(address _trader) external view returns (address)
```

*Returns active referrer of trader*

### Parameters

| Name     | Type    | Description       |
| -------- | ------- | ----------------- |
| \_trader | address | address of trader |

## getReferrersReferred

```solidity
function getReferrersReferred(address _ally) external view returns (address[])
```

*Returns referrers referred by ally*

### Parameters

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| \_ally | address | address of ally |

## getTradersReferred

```solidity
function getTradersReferred(address _referrer) external view returns (address[])
```

*Returns traders referred by referrer*

### Parameters

| Name       | Type    | Description         |
| ---------- | ------- | ------------------- |
| \_referrer | address | address of referrer |

## getReferralsAllyFeeP

```solidity
function getReferralsAllyFeeP() external view returns (uint256)
```

*Returns ally fee % of total referral fee*

## getReferralsStartReferrerFeeP

```solidity
function getReferralsStartReferrerFeeP() external view returns (uint256)
```

*Returns start referrer fee % of total referral fee when zero volume was referred*

## getReferralsTargetVolumeUsd

```solidity
function getReferralsTargetVolumeUsd() external view returns (uint256)
```

*Returns target volume in usd to reach 100% of referral fee*

## getAllyDetails

```solidity
function getAllyDetails(address _ally) external view returns (struct IReferrals.AllyDetails)
```

*Returns ally details*

### Parameters

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| \_ally | address | address of ally |

## getReferrerDetails

```solidity
function getReferrerDetails(address _referrer) external view returns (struct IReferrals.ReferrerDetails)
```

*Returns referrer details*

### Parameters

| Name       | Type    | Description         |
| ---------- | ------- | ------------------- |
| \_referrer | address | address of referrer |


# GNSTradingCallbacks

*Facet #8: Callbacks (to execute actions after receiving median price from price aggregator)*

## constructor

```solidity
constructor() public
```

## initializeCallbacks

```solidity
function initializeCallbacks(uint8 _vaultClosingFeeP) external
```

### Parameters

| Name               | Type  | Description                         |
| ------------------ | ----- | ----------------------------------- |
| \_vaultClosingFeeP | uint8 | the % of closing fee going to vault |

## initializeTreasuryAddress

```solidity
function initializeTreasuryAddress(address _treasury) external
```

*Initialize the treasury address*

### Parameters

| Name       | Type    | Description          |
| ---------- | ------- | -------------------- |
| \_treasury | address | the treasury address |

## updateVaultClosingFeeP

```solidity
function updateVaultClosingFeeP(uint8 _valueP) external
```

*Update the % of closing fee going to vault*

### Parameters

| Name     | Type  | Description                         |
| -------- | ----- | ----------------------------------- |
| \_valueP | uint8 | the % of closing fee going to vault |

## updateTreasuryAddress

```solidity
function updateTreasuryAddress(address _treasury) external
```

*Updates the treasury address*

### Parameters

| Name       | Type    | Description              |
| ---------- | ------- | ------------------------ |
| \_treasury | address | the new treasury address |

## claimPendingGovFees

```solidity
function claimPendingGovFees() external
```

*Claim the pending gov fees for all collaterals*

## openTradeMarketCallback

```solidity
function openTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending open trade market order*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## closeTradeMarketCallback

```solidity
function closeTradeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending close trade market order*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## executeTriggerOpenOrderCallback

```solidity
function executeTriggerOpenOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending open trigger order (for limit/stop orders)*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## executeTriggerCloseOrderCallback

```solidity
function executeTriggerCloseOrderCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending close trigger order (for tp/sl/liq orders)*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## getVaultClosingFeeP

```solidity
function getVaultClosingFeeP() external view returns (uint8)
```

*Returns the current vaultClosingFeeP value (%)*

## getPendingGovFeesCollateral

```solidity
function getPendingGovFeesCollateral(uint8 _collateralIndex) external view returns (uint256)
```

*Returns the current pending gov fees for a collateral index (collateral precision)*

## updateLeverageCallback

```solidity
function updateLeverageCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending update leverage order*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## increasePositionSizeMarketCallback

```solidity
function increasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending increase position size market order*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## decreasePositionSizeMarketCallback

```solidity
function decreasePositionSizeMarketCallback(struct ITradingCallbacks.AggregatorAnswer _a) external virtual
```

*Executes a pending decrease position size market order*

### Parameters

| Name | Type                                                                                                                               | Description                                         |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| \_a  | [ITradingCallbacks.AggregatorAnswer](/developer/technical-reference/contracts/interfaces/types/itradingcallbacks#aggregatoranswer) | the price aggregator answer (order id, price, etc.) |

## validateTriggerOpenOrderCallback

```solidity
function validateTriggerOpenOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v)
```

*Makes open trigger (STOP/LIMIT) checks like slippage, price impact, missed targets and returns cancellation reason if any*

### Parameters

| Name        | Type                                                                                               | Description                                |
| ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| \_tradeId   | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade                        |
| \_orderType | enum ITradingStorage.PendingOrderType                                                              | the pending order type                     |
| \_open      | uint64                                                                                             | the `open` value from an aggregator answer |
| \_high      | uint64                                                                                             | the `high` value from an aggregator answer |
| \_low       | uint64                                                                                             | the `low` value from an aggregator answer  |

## validateTriggerCloseOrderCallback

```solidity
function validateTriggerCloseOrderCallback(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType, uint64 _open, uint64 _high, uint64 _low) external view returns (struct ITradingStorage.Trade t, enum ITradingCallbacks.CancelReason cancelReason, struct ITradingCallbacks.Values v)
```

*Makes close trigger (SL/TP/LIQ) checks like slippage and price impact and returns cancellation reason if any*

### Parameters

| Name        | Type                                                                                               | Description                                |
| ----------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| \_tradeId   | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the trade                        |
| \_orderType | enum ITradingStorage.PendingOrderType                                                              | the pending order type                     |
| \_open      | uint64                                                                                             | the `open` value from an aggregator answer |
| \_high      | uint64                                                                                             | the `high` value from an aggregator answer |
| \_low       | uint64                                                                                             | the `low` value from an aggregator answer  |


# GNSTradingStorage

*Facet #5: Trading storage*

## constructor

```solidity
constructor() public
```

## initializeTradingStorage

```solidity
function initializeTradingStorage(address _gns, address _gnsStaking, address[] _collaterals, address[] _gTokens) external
```

*Initializes the trading storage facet*

### Parameters

| Name          | Type       | Description                         |
| ------------- | ---------- | ----------------------------------- |
| \_gns         | address    | address of the gns token            |
| \_gnsStaking  | address    | address of the gns staking contract |
| \_collaterals | address\[] |                                     |
| \_gTokens     | address\[] |                                     |

## updateTradingActivated

```solidity
function updateTradingActivated(enum ITradingStorage.TradingActivated _activated) external
```

*Updates the trading activated state*

### Parameters

| Name        | Type                                  | Description                     |
| ----------- | ------------------------------------- | ------------------------------- |
| \_activated | enum ITradingStorage.TradingActivated | the new trading activated state |

## addCollateral

```solidity
function addCollateral(address _collateral, address _gToken) external
```

*Adds a new supported collateral*

### Parameters

| Name         | Type    | Description                           |
| ------------ | ------- | ------------------------------------- |
| \_collateral | address | the address of the collateral         |
| \_gToken     | address | the gToken contract of the collateral |

## toggleCollateralActiveState

```solidity
function toggleCollateralActiveState(uint8 _collateralIndex) external
```

*Toggles the active state of a supported collateral*

### Parameters

| Name              | Type  | Description             |
| ----------------- | ----- | ----------------------- |
| \_collateralIndex | uint8 | index of the collateral |

## updateGToken

```solidity
function updateGToken(address _collateral, address _gToken) external
```

*Updates the contracts of a supported collateral trading stack*

### Parameters

| Name         | Type    | Description                           |
| ------------ | ------- | ------------------------------------- |
| \_collateral | address | address of the collateral             |
| \_gToken     | address | the gToken contract of the collateral |

## storeTrade

```solidity
function storeTrade(struct ITradingStorage.Trade _trade, struct ITradingStorage.TradeInfo _tradeInfo) external virtual returns (struct ITradingStorage.Trade)
```

*Stores a new trade (trade/limit/stop)*

### Parameters

| Name        | Type                                                                                                             | Description             |
| ----------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_trade     | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage#trade)         | trade to be stored      |
| \_tradeInfo | [ITradingStorage.TradeInfo](/developer/technical-reference/contracts/interfaces/types/itradingstorage#tradeinfo) | trade info to be stored |

## updateTradeMaxClosingSlippageP

```solidity
function updateTradeMaxClosingSlippageP(struct ITradingStorage.Id _tradeId, uint16 _maxSlippageP) external virtual
```

*Updates an existing trade max closing slippage %*

### Parameters

| Name           | Type                                                                                               | Description                        |
| -------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------- |
| \_tradeId      | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade                    |
| \_maxSlippageP | uint16                                                                                             | new max slippage % (1e3 precision) |

## updateTradeCollateralAmount

```solidity
function updateTradeCollateralAmount(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount) external virtual
```

*Updates an open trade collateral*

### Parameters

| Name               | Type                                                                                               | Description                                        |
| ------------------ | -------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| \_tradeId          | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade                                |
| \_collateralAmount | uint120                                                                                            | new collateral amount value (collateral precision) |

## updateTradePosition

```solidity
function updateTradePosition(struct ITradingStorage.Id _tradeId, uint120 _collateralAmount, uint24 _leverage, uint64 _openPrice, bool _isPartialIncrease, bool _isPnlPositive) external virtual
```

*Updates an open trade collateral*

### Parameters

| Name                | Type                                                                                               | Description                                              |
| ------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| \_tradeId           | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade                                      |
| \_collateralAmount  | uint120                                                                                            | new collateral amount value (collateral precision)       |
| \_leverage          | uint24                                                                                             | new leverage value                                       |
| \_openPrice         | uint64                                                                                             | new open price value                                     |
| \_isPartialIncrease | bool                                                                                               | refreshes trade liquidation params if true               |
| \_isPnlPositive     | bool                                                                                               | whether the pnl is positive (only relevant when closing) |

## updateOpenOrderDetails

```solidity
function updateOpenOrderDetails(struct ITradingStorage.Id _tradeId, uint64 _openPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external virtual
```

*Updates an open order details (limit/stop)*

### Parameters

| Name           | Type                                                                                               | Description                    |
| -------------- | -------------------------------------------------------------------------------------------------- | ------------------------------ |
| \_tradeId      | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of updated trade            |
| \_openPrice    | uint64                                                                                             | new open price (1e10)          |
| \_tp           | uint64                                                                                             | new take profit price (1e10)   |
| \_sl           | uint64                                                                                             | new stop loss price (1e10)     |
| \_maxSlippageP | uint16                                                                                             | new max slippage % value (1e3) |

## updateTradeTp

```solidity
function updateTradeTp(struct ITradingStorage.Id _tradeId, uint64 _newTp) external virtual
```

*Updates the take profit of an open trade*

### Parameters

| Name      | Type                                                                                               | Description                          |
| --------- | -------------------------------------------------------------------------------------------------- | ------------------------------------ |
| \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id                         |
| \_newTp   | uint64                                                                                             | the new take profit (1e10 precision) |

## updateTradeSl

```solidity
function updateTradeSl(struct ITradingStorage.Id _tradeId, uint64 _newSl) external virtual
```

*Updates the stop loss of an open trade*

### Parameters

| Name      | Type                                                                                               | Description                 |
| --------- | -------------------------------------------------------------------------------------------------- | --------------------------- |
| \_tradeId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id                |
| \_newSl   | uint64                                                                                             | the new sl (1e10 precision) |

## closeTrade

```solidity
function closeTrade(struct ITradingStorage.Id _tradeId, bool _isPnlPositive) external virtual
```

*Marks an open trade/limit/stop as closed*

### Parameters

| Name            | Type                                                                                               | Description                 |
| --------------- | -------------------------------------------------------------------------------------------------- | --------------------------- |
| \_tradeId       | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the trade id                |
| \_isPnlPositive | bool                                                                                               | whether the pnl is positive |

## storePendingOrder

```solidity
function storePendingOrder(struct ITradingStorage.PendingOrder _pendingOrder) external virtual returns (struct ITradingStorage.PendingOrder)
```

*Stores a new pending order*

### Parameters

| Name           | Type                                                                                                                   | Description                    |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| \_pendingOrder | [ITradingStorage.PendingOrder](/developer/technical-reference/contracts/interfaces/types/itradingstorage#pendingorder) | the pending order to be stored |

## closePendingOrder

```solidity
function closePendingOrder(struct ITradingStorage.Id _orderId) external virtual
```

*Closes a pending order*

### Parameters

| Name      | Type                                                                                               | Description                              |
| --------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------- |
| \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | the id of the pending order to be closed |

## getCollateral

```solidity
function getCollateral(uint8 _index) external view returns (struct ITradingStorage.Collateral)
```

*Returns collateral data by index*

### Parameters

| Name    | Type  | Description                           |
| ------- | ----- | ------------------------------------- |
| \_index | uint8 | the index of the supported collateral |

## isCollateralActive

```solidity
function isCollateralActive(uint8 _index) external view returns (bool)
```

*Returns whether can open new trades with a collateral*

### Parameters

| Name    | Type  | Description                          |
| ------- | ----- | ------------------------------------ |
| \_index | uint8 | the index of the collateral to check |

## isCollateralListed

```solidity
function isCollateralListed(uint8 _index) external view returns (bool)
```

*Returns whether a collateral has been listed*

### Parameters

| Name    | Type  | Description                          |
| ------- | ----- | ------------------------------------ |
| \_index | uint8 | the index of the collateral to check |

## getCollateralsCount

```solidity
function getCollateralsCount() external view returns (uint8)
```

*Returns the number of supported collaterals*

## getCollaterals

```solidity
function getCollaterals() external view returns (struct ITradingStorage.Collateral[])
```

*Returns the supported collaterals*

## getCollateralIndex

```solidity
function getCollateralIndex(address _collateral) external view returns (uint8)
```

*Returns the index of a supported collateral*

### Parameters

| Name         | Type    | Description                   |
| ------------ | ------- | ----------------------------- |
| \_collateral | address | the address of the collateral |

## getTradingActivated

```solidity
function getTradingActivated() external view returns (enum ITradingStorage.TradingActivated)
```

*Returns the trading activated state*

## getTraderStored

```solidity
function getTraderStored(address _trader) external view returns (bool)
```

*Returns whether a trader is stored in the traders array*

### Parameters

| Name     | Type    | Description     |
| -------- | ------- | --------------- |
| \_trader | address | trader to check |

## getTradersCount

```solidity
function getTradersCount() external view returns (uint256)
```

*Returns the length of the traders array*

## getTraders

```solidity
function getTraders(uint32 _offset, uint32 _limit) external view returns (address[])
```

*Returns all traders that have open trades using a pagination system*

### Parameters

| Name     | Type   | Description                      |
| -------- | ------ | -------------------------------- |
| \_offset | uint32 | start index in the traders array |
| \_limit  | uint32 | end index in the traders array   |

## getTrade

```solidity
function getTrade(address _trader, uint32 _index) external view returns (struct ITradingStorage.Trade)
```

*Returns open trade/limit/stop order*

### Parameters

| Name     | Type    | Description                   |
| -------- | ------- | ----------------------------- |
| \_trader | address | address of the trader         |
| \_index  | uint32  | index of the trade for trader |

## getTrades

```solidity
function getTrades(address _trader) external view returns (struct ITradingStorage.Trade[])
```

*Returns all open trades/limit/stop orders for a trader*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_trader | address | address of the trader |

## getAllTradesForTraders

```solidity
function getAllTradesForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[])
```

*Returns all trade/limit/stop orders using a pagination system*

### Parameters

| Name      | Type       | Description                          |
| --------- | ---------- | ------------------------------------ |
| \_traders | address\[] | list of traders to return trades for |
| \_offset  | uint256    | index of first trade to return       |
| \_limit   | uint256    | index of last trade to return        |

## getAllTrades

```solidity
function getAllTrades(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.Trade[])
```

*Returns all trade/limit/stop orders using a pagination system. Calls `getAllTradesForTraders` internally with all traders.*

### Parameters

| Name     | Type    | Description                    |
| -------- | ------- | ------------------------------ |
| \_offset | uint256 | index of first trade to return |
| \_limit  | uint256 | index of last trade to return  |

## getTradeInfo

```solidity
function getTradeInfo(address _trader, uint32 _index) external view returns (struct ITradingStorage.TradeInfo)
```

*Returns trade info of an open trade/limit/stop order*

### Parameters

| Name     | Type    | Description                   |
| -------- | ------- | ----------------------------- |
| \_trader | address | address of the trader         |
| \_index  | uint32  | index of the trade for trader |

## getTradeInfos

```solidity
function getTradeInfos(address _trader) external view returns (struct ITradingStorage.TradeInfo[])
```

*Returns all trade infos of open trade/limit/stop orders for a trader*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_trader | address | address of the trader |

## getAllTradeInfosForTraders

```solidity
function getAllTradeInfosForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[])
```

*Returns all trade infos of open trade/limit/stop orders using a pagination system*

### Parameters

| Name      | Type       | Description                             |
| --------- | ---------- | --------------------------------------- |
| \_traders | address\[] | list of traders to return tradeInfo for |
| \_offset  | uint256    | index of first tradeInfo to return      |
| \_limit   | uint256    | index of last tradeInfo to return       |

## getAllTradeInfos

```solidity
function getAllTradeInfos(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.TradeInfo[])
```

*Returns all trade infos of open trade/limit/stop orders using a pagination system. Calls `getAllTradeInfosForTraders` internally with all traders.*

### Parameters

| Name     | Type    | Description                        |
| -------- | ------- | ---------------------------------- |
| \_offset | uint256 | index of first tradeInfo to return |
| \_limit  | uint256 | index of last tradeInfo to return  |

## getPendingOrder

```solidity
function getPendingOrder(struct ITradingStorage.Id _orderId) external view returns (struct ITradingStorage.PendingOrder)
```

*Returns a pending ordeer*

### Parameters

| Name      | Type                                                                                               | Description             |
| --------- | -------------------------------------------------------------------------------------------------- | ----------------------- |
| \_orderId | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the pending order |

## getPendingOrders

```solidity
function getPendingOrders(address _user) external view returns (struct ITradingStorage.PendingOrder[])
```

*Returns all pending orders for a trader*

### Parameters

| Name   | Type    | Description           |
| ------ | ------- | --------------------- |
| \_user | address | address of the trader |

## getAllPendingOrdersForTraders

```solidity
function getAllPendingOrdersForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[])
```

*Returns all pending orders using a pagination system*

### Parameters

| Name      | Type       | Description                                |
| --------- | ---------- | ------------------------------------------ |
| \_traders | address\[] | list of traders to return pendingOrder for |
| \_offset  | uint256    | index of first pendingOrder to return      |
| \_limit   | uint256    | index of last pendingOrder to return       |

## getAllPendingOrders

```solidity
function getAllPendingOrders(uint256 _offset, uint256 _limit) external view returns (struct ITradingStorage.PendingOrder[])
```

*Returns all pending orders using a pagination system Calls `getAllPendingOrdersForTraders` internally with all traders.*

### Parameters

| Name     | Type    | Description                           |
| -------- | ------- | ------------------------------------- |
| \_offset | uint256 | index of first pendingOrder to return |
| \_limit  | uint256 | index of last pendingOrder to return  |

## getTradePendingOrderBlock

```solidity
function getTradePendingOrderBlock(struct ITradingStorage.Id _tradeId, enum ITradingStorage.PendingOrderType _orderType) external view returns (uint256)
```

*Returns the block number of the pending order for a trade (0 = doesn't exist)*

### Parameters

| Name        | Type                                                                                               | Description                 |
| ----------- | -------------------------------------------------------------------------------------------------- | --------------------------- |
| \_tradeId   | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | id of the trade             |
| \_orderType | enum ITradingStorage.PendingOrderType                                                              | pending order type to check |

## getCounters

```solidity
function getCounters(address _trader, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter)
```

*Returns the counters of a trader (currentIndex / open count for trades/tradeInfos and pendingOrders mappings)*

### Parameters

| Name     | Type                             | Description                            |
| -------- | -------------------------------- | -------------------------------------- |
| \_trader | address                          | address of the trader                  |
| \_type   | enum ITradingStorage.CounterType | the counter type (trade/pending order) |

## getCountersForTraders

```solidity
function getCountersForTraders(address[] _traders, enum ITradingStorage.CounterType _type) external view returns (struct ITradingStorage.Counter[])
```

*Returns the counters for a list of traders*

### Parameters

| Name      | Type                             | Description                            |
| --------- | -------------------------------- | -------------------------------------- |
| \_traders | address\[]                       | the list of traders                    |
| \_type    | enum ITradingStorage.CounterType | the counter type (trade/pending order) |

## getGToken

```solidity
function getGToken(uint8 _collateralIndex) external view returns (address)
```

*Returns the address of the gToken for a collateral stack*

### Parameters

| Name              | Type  | Description                           |
| ----------------- | ----- | ------------------------------------- |
| \_collateralIndex | uint8 | the index of the supported collateral |

## getTradeLiquidationParams

```solidity
function getTradeLiquidationParams(address _trader, uint32 _index) external view returns (struct IPairsStorage.GroupLiquidationParams)
```

*Returns the liquidation params for a trade*

### Parameters

| Name     | Type    | Description                   |
| -------- | ------- | ----------------------------- |
| \_trader | address | address of the trader         |
| \_index  | uint32  | index of the trade for trader |

## getTradesLiquidationParams

```solidity
function getTradesLiquidationParams(address _trader) external view returns (struct IPairsStorage.GroupLiquidationParams[])
```

*Returns all trade liquidation params of open trade/limit/stop orders for a trader*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_trader | address | address of the trader |

## getAllTradesLiquidationParamsForTraders

```solidity
function getAllTradesLiquidationParamsForTraders(address[] _traders, uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[])
```

*Returns all trade liquidation params of open trade/limit/stop orders using a pagination system*

### Parameters

| Name      | Type       | Description                              |
| --------- | ---------- | ---------------------------------------- |
| \_traders | address\[] | list of traders to return liq params for |
| \_offset  | uint256    | index of first liq param to return       |
| \_limit   | uint256    | index of last liq param to return        |

## getAllTradesLiquidationParams

```solidity
function getAllTradesLiquidationParams(uint256 _offset, uint256 _limit) external view returns (struct IPairsStorage.GroupLiquidationParams[])
```

*Returns all trade liquidation params of open trade/limit/stop orders using a pagination system Calls `getAllTradesLiquidationParamsForTraders` internally with all traders.*

### Parameters

| Name     | Type    | Description                        |
| -------- | ------- | ---------------------------------- |
| \_offset | uint256 | index of first liq param to return |
| \_limit  | uint256 | index of last liq param to return  |

## getCurrentContractsVersion

```solidity
function getCurrentContractsVersion() external pure returns (enum ITradingStorage.ContractsVersion)
```

*Returns the current contracts version*


# GNSMultiCollatDiamond

*Diamond that contains all code for the gTrade leverage trading platform*

{% file src="/files/hJFnQOm8d3mjVbW14zgc" %}

**Please refer to** [Facets](/developer/technical-reference/contracts/core/facets) **for list of facets and functions they support.** \
**Essential Diamond facets like DiamondCut, Loupe and other Access-Control related facets can be found in** [Abstract](/developer/technical-reference/contracts/core/abstract)


# GNSStaking

*Staking contract for GNS token to earn in multiple reward tokens from fees generated on gTrade.*

## gns

```solidity
contract IERC20 gns
```

## dai

```solidity
contract IERC20 dai
```

## accDaiPerToken

```solidity
uint128 accDaiPerToken
```

## gnsBalance

```solidity
uint128 gnsBalance
```

## stakers

```solidity
mapping(address => struct IGNSStaking.Staker) stakers
```

## unlockManagers

```solidity
mapping(address => bool) unlockManagers
```

## rewardTokens

```solidity
address[] rewardTokens
```

## rewardTokenState

```solidity
mapping(address => struct IGNSStaking.RewardState) rewardTokenState
```

## userTokenRewards

```solidity
mapping(address => mapping(address => struct IGNSStaking.RewardInfo)) userTokenRewards
```

## userTokenUnlockRewards

```solidity
mapping(address => mapping(address => mapping(uint256 => struct IGNSStaking.RewardInfo))) userTokenUnlockRewards
```

## stakerInfos

```solidity
mapping(address => struct IGNSStaking.StakerInfo) stakerInfos
```

## constructor

```solidity
constructor() public
```

## initialize

```solidity
function initialize(address _owner, contract IERC20 _gns, contract IERC20 _dai) external
```

*Sets `owner` and initializes `dai` and `gns` state variables*

## initializeV2

```solidity
function initializeV2() external
```

*Add `dai` as a reward token (old stakers.debtDai, unlockSchedules.debtDai and accDaiPerToken are deprecacted now) Necessary to call right after contract is updated because otherwise distributeRewardDai() reverts.*

## onlyAuthorizedUnlockManager

```solidity
modifier onlyAuthorizedUnlockManager(address _staker, bool _revocable)
```

*Modifier used for vest creation access control. Users can create non-revocable vests for themselves only, `owner` and `unlockManagers` can create both types for anyone.*

## onlyRewardToken

```solidity
modifier onlyRewardToken(address _token)
```

*Modifier to reject any `_token` not configured as a reward token*

## notInCooldown

```solidity
modifier notInCooldown()
```

*Modifier to ensure operation is not performed before cooldown period has expired*

## setUnlockManager

```solidity
function setUnlockManager(address _manager, bool _authorized) external
```

\_Sets whether `_manager` is `_authorized` to create vests for other users.

Emits {UnlockManagerUpdated}\_

## addRewardToken

```solidity
function addRewardToken(address _token) external
```

\_Forwards call to {*addRewardToken}. Only callable by `owner`.*

## setDelegatee

```solidity
function setDelegatee(address _token, address _delegatee) external
```

*Attempts to set the delegatee of `_token` to `_delegatee`. `_token` must be a valid reward token.*

## unlockedGns

```solidity
function unlockedGns(struct IGNSStaking.UnlockSchedule _schedule, uint48 _timestamp) public pure returns (uint128)
```

*Returns the unlocked GNS tokens amount of `_schedule` at `_timestamp`. Includes already claimed GNS tokens.*

## releasableGns

```solidity
function releasableGns(struct IGNSStaking.UnlockSchedule _schedule, uint48 _timestamp) public pure returns (uint128)
```

*Returns the releasable GNS tokens amount (1e18 precision) of `_schedule` at `_timestamp`. Doesn't include already claimed GNS tokens.*

## owner

```solidity
function owner() public view returns (address)
```

*Returns the owner of the contract.*

## isRewardToken

```solidity
function isRewardToken(address _token) public view returns (bool)
```

*Returns whether `_token` is a listed reward token.*

## distributeReward

```solidity
function distributeReward(address _token, uint256 _amountToken) external
```

\_Transfers `_amountToken` of `_token` (valid reward token) from caller to this contract and updates `accRewardPerGns`.

Note: `accRewardPerGns` is normalized to 1e18 for all reward tokens (even those with less than 18 decimals)

Emits {RewardDistributed}\_

## harvestToken

```solidity
function harvestToken(address _token) public returns (uint128)
```

*Harvests the caller's regular pending `_token` rewards. `_token` must be a valid reward token.*

## harvestTokenFromUnlock

```solidity
function harvestTokenFromUnlock(address _token, uint256[] _ids) public returns (uint128)
```

*Harvests the caller's pending `_token` rewards for vests `_ids`. `_token` must be a valid reward token.*

## harvestTokenAll

```solidity
function harvestTokenAll(address _token, uint256[] _ids) public returns (uint128)
```

*Harvests the caller's regular pending `_token` rewards and pending rewards for vests `_ids`.*

## harvestTokens

```solidity
function harvestTokens() public
```

*Harvests the caller's regular pending rewards for all supported reward tokens.*

## harvestTokensFromUnlock

```solidity
function harvestTokensFromUnlock(uint256[] _ids) public
```

*Harvests the caller's pending rewards of vests `_ids` for all supported reward tokens.*

## harvestTokensAll

```solidity
function harvestTokensAll(uint256[] _ids) public
```

*Harvests the caller's regular pending rewards and pending rewards of vests `_ids` for all supported reward tokens.*

## compoundGnsRewards

```solidity
function compoundGnsRewards(uint256[] _ids) external
```

*Harvests the caller's GNS pending rewards and then stakes them*

## harvestDai

```solidity
function harvestDai() public
```

*Harvests caller's old regular dai rewards.*

## harvestDaiFromUnlock

```solidity
function harvestDaiFromUnlock(uint256[] _ids) public
```

*Harvests caller's old dai rewards for vests `_ids`.*

## harvestDaiAll

```solidity
function harvestDaiAll(uint256[] _ids) public
```

*Harvests caller's old regular dai rewards and old dai rewards of vests `_ids`.*

## harvestAll

```solidity
function harvestAll(uint256[] _ids) external
```

*Harvests the caller's regular pending rewards and pending rewards for vests `_ids` for all supported reward tokens (+ old DAI rewards).*

## stakeGns

```solidity
function stakeGns(uint128 _amountGns) public
```

\_Stakes non-vested `_amountGns` from caller.

Emits {GnsStaked}\_

## unstakeGns

```solidity
function unstakeGns(uint128 _amountGns) external
```

\_Unstakes non-vested `_amountGns` from caller.

Emits {GnsUnstaked}\_

## claimUnlockedGns

```solidity
function claimUnlockedGns(uint256[] _ids) external
```

*Claims caller's unlocked GNS from vests `_ids`.*

## createUnlockSchedule

```solidity
function createUnlockSchedule(struct IGNSStaking.UnlockScheduleInput _schedule, address _staker) external
```

\_Creates vest for `_staker` given `_schedule` input parameters. Restricted with onlyAuthorizedUnlockManager access control.

Emits {UnlockScheduled}\_

## revokeUnlockSchedule

```solidity
function revokeUnlockSchedule(address _staker, uint256 _id) external
```

\_Revokes vest `_id` for `_staker`. Sends the unlocked GNS to `_staker` and sends the remaining locked GNS to `owner`. Only callable by `owner`.

Emits {UnlockScheduleRevoked}\_

## pendingRewardToken

```solidity
function pendingRewardToken(address _staker, address _token) public view returns (uint128)
```

*Returns the pending `_token` rewards (precision depends on token) for `_staker`.*

## pendingRewardTokens

```solidity
function pendingRewardTokens(address _staker) external view returns (uint128[] pendingTokens)
```

*Returns an array of `_staker`'s pending rewards (precision depends on token) for all supported tokens.*

## pendingRewardTokensFromUnlocks

```solidity
function pendingRewardTokensFromUnlocks(address _staker, uint256[] _ids) external view returns (uint128[] pendingTokens)
```

*Returns an array of `_staker`'s pending rewards (precision depends on token) from vests `_ids` for all supported tokens.*

## pendingRewardDai

```solidity
function pendingRewardDai(address _staker) external view returns (uint128)
```

*Returns `_staker`'s pending old dai rewards (1e18 precision).*

## pendingRewardDaiFromUnlocks

```solidity
function pendingRewardDaiFromUnlocks(address _staker, uint256[] _ids) external view returns (uint128 pending)
```

*Returns `_staker`'s pending old dai rewards (1e18 precision) from vests `_ids`.*

## totalGnsStaked

```solidity
function totalGnsStaked(address _staker) external view returns (uint128)
```

*Returns `_staker's` total non-vested and vested GNS staked (1e18 precision)*

## getUnlockSchedules

```solidity
function getUnlockSchedules(address _staker) external view returns (struct IGNSStaking.UnlockSchedule[])
```

*Returns all `_staker's` vests.*

## getUnlockSchedules

```solidity
function getUnlockSchedules(address _staker, uint256 _index) external view returns (struct IGNSStaking.UnlockSchedule)
```

*Returns `_staker's` vest at `_index'`*

## getRewardTokens

```solidity
function getRewardTokens() external view returns (address[])
```

*Returns the address of all supported reward tokens*


# GToken

*GToken vault contract, direct counterparty to trades happening on gTrade*

## gnsToken

```solidity
address gnsToken
```

## lockedDepositNft

```solidity
contract IGTokenLockedDepositNft lockedDepositNft
```

## manager

```solidity
address manager
```

## admin

```solidity
address admin
```

## pnlHandler

```solidity
address pnlHandler
```

## openTradesPnlFeed

```solidity
contract IGTokenOpenPnlFeed openTradesPnlFeed
```

## gnsPriceProvider

```solidity
struct IGToken.GnsPriceProvider gnsPriceProvider
```

## PRECISION\_18

```solidity
uint256 PRECISION_18
```

## PRECISION\_10

```solidity
uint256 PRECISION_10
```

## MIN\_DAILY\_ACC\_PNL\_DELTA

```solidity
uint256 MIN_DAILY_ACC_PNL_DELTA
```

## MAX\_SUPPLY\_INCREASE\_DAILY\_P

```solidity
uint256 MAX_SUPPLY_INCREASE_DAILY_P
```

## MAX\_LOSSES\_BURN\_P

```solidity
uint256 MAX_LOSSES_BURN_P
```

## MAX\_GNS\_SUPPLY\_MINT\_DAILY\_P

```solidity
uint256 MAX_GNS_SUPPLY_MINT_DAILY_P
```

## MAX\_DISCOUNT\_P

```solidity
uint256 MAX_DISCOUNT_P
```

## MIN\_LOCK\_DURATION

```solidity
uint256 MIN_LOCK_DURATION
```

## MAX\_LOCK\_DURATION

```solidity
uint256 MAX_LOCK_DURATION
```

## WITHDRAW\_EPOCHS\_LOCKS

```solidity
uint256[] WITHDRAW_EPOCHS_LOCKS
```

## maxAccOpenPnlDelta

```solidity
uint256 maxAccOpenPnlDelta
```

## maxDailyAccPnlDelta

```solidity
uint256 maxDailyAccPnlDelta
```

## withdrawLockThresholdsP

```solidity
uint256[2] withdrawLockThresholdsP
```

## maxSupplyIncreaseDailyP

```solidity
uint256 maxSupplyIncreaseDailyP
```

## lossesBurnP

```solidity
uint256 lossesBurnP
```

## maxGnsSupplyMintDailyP

```solidity
uint256 maxGnsSupplyMintDailyP
```

## maxDiscountP

```solidity
uint256 maxDiscountP
```

## maxDiscountThresholdP

```solidity
uint256 maxDiscountThresholdP
```

## shareToAssetsPrice

```solidity
uint256 shareToAssetsPrice
```

## accPnlPerTokenUsed

```solidity
int256 accPnlPerTokenUsed
```

## accPnlPerToken

```solidity
int256 accPnlPerToken
```

## accRewardsPerToken

```solidity
uint256 accRewardsPerToken
```

## dailyAccPnlDelta

```solidity
int256 dailyAccPnlDelta
```

## lastDailyAccPnlDeltaReset

```solidity
uint256 lastDailyAccPnlDeltaReset
```

## currentEpoch

```solidity
uint256 currentEpoch
```

## currentEpochStart

```solidity
uint256 currentEpochStart
```

## currentEpochPositiveOpenPnl

```solidity
uint256 currentEpochPositiveOpenPnl
```

## currentMaxSupply

```solidity
uint256 currentMaxSupply
```

## lastMaxSupplyUpdate

```solidity
uint256 lastMaxSupplyUpdate
```

## withdrawRequests

```solidity
mapping(address => mapping(uint256 => uint256)) withdrawRequests
```

## lockedDepositsCount

```solidity
uint256 lockedDepositsCount
```

## lockedDeposits

```solidity
mapping(uint256 => struct IGToken.LockedDeposit) lockedDeposits
```

## assetsToDeplete

```solidity
uint256 assetsToDeplete
```

## dailyMintedGns

```solidity
uint256 dailyMintedGns
```

## lastDailyMintedGnsReset

```solidity
uint256 lastDailyMintedGnsReset
```

## totalDeposited

```solidity
uint256 totalDeposited
```

## totalClosedPnl

```solidity
int256 totalClosedPnl
```

## totalRewards

```solidity
uint256 totalRewards
```

## totalLiability

```solidity
int256 totalLiability
```

## totalLockedDiscounts

```solidity
uint256 totalLockedDiscounts
```

## totalDiscounts

```solidity
uint256 totalDiscounts
```

## totalDepleted

```solidity
uint256 totalDepleted
```

## totalDepletedGns

```solidity
uint256 totalDepletedGns
```

## totalRefilled

```solidity
uint256 totalRefilled
```

## totalRefilledGns

```solidity
uint256 totalRefilledGns
```

## accBlockWeightedMarketCap

```solidity
uint256 accBlockWeightedMarketCap
```

## accBlockWeightedMarketCapLastStored

```solidity
uint256 accBlockWeightedMarketCapLastStored
```

## collateralConfig

```solidity
struct CollateralUtils.CollateralConfig collateralConfig
```

## initialize

```solidity
function initialize(struct IGToken.Meta _meta, struct IGToken.ContractAddresses _contractAddresses, uint256 _MIN_LOCK_DURATION, uint256 _maxAccOpenPnlDelta, uint256 _maxDailyAccPnlDelta, uint256[2] _withdrawLockThresholdsP, uint256 _maxSupplyIncreaseDailyP, uint256 _lossesBurnP, uint256 _maxGnsSupplyMintDailyP, uint256 _maxDiscountP, uint256 _maxDiscountThresholdP) external
```

## initializeV3

```solidity
function initializeV3() external
```

## onlyManager

```solidity
modifier onlyManager()
```

## checks

```solidity
modifier checks(uint256 assetsOrShares)
```

## validDiscount

```solidity
modifier validDiscount(uint256 lockDuration)
```

## transferOwnership

```solidity
function transferOwnership(address newOwner) public
```

*Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.*

## updateManager

```solidity
function updateManager(address newValue) external
```

## updateAdmin

```solidity
function updateAdmin(address newValue) external
```

## updatePnlHandler

```solidity
function updatePnlHandler(address newValue) external
```

## updateGnsPriceProvider

```solidity
function updateGnsPriceProvider(struct IGToken.GnsPriceProvider newValue) external
```

## updateOpenTradesPnlFeed

```solidity
function updateOpenTradesPnlFeed(address newValue) external
```

## updateDelegatee

```solidity
function updateDelegatee(address _delegatee) external
```

## updateMaxAccOpenPnlDelta

```solidity
function updateMaxAccOpenPnlDelta(uint256 newValue) external
```

## updateMaxDailyAccPnlDelta

```solidity
function updateMaxDailyAccPnlDelta(uint256 newValue) external
```

## updateWithdrawLockThresholdsP

```solidity
function updateWithdrawLockThresholdsP(uint256[2] newValue) external
```

## updateMaxSupplyIncreaseDailyP

```solidity
function updateMaxSupplyIncreaseDailyP(uint256 newValue) external
```

## updateLossesBurnP

```solidity
function updateLossesBurnP(uint256 newValue) external
```

## updateMaxGnsSupplyMintDailyP

```solidity
function updateMaxGnsSupplyMintDailyP(uint256 newValue) external
```

## updateMaxDiscountP

```solidity
function updateMaxDiscountP(uint256 newValue) external
```

## updateMaxDiscountThresholdP

```solidity
function updateMaxDiscountThresholdP(uint256 newValue) external
```

## maxAccPnlPerToken

```solidity
function maxAccPnlPerToken() public view returns (uint256)
```

## collateralizationP

```solidity
function collateralizationP() public view returns (uint256)
```

## gnsTokenToAssetsPrice

```solidity
function gnsTokenToAssetsPrice() public view returns (uint256 price)
```

## withdrawEpochsTimelock

```solidity
function withdrawEpochsTimelock() public view returns (uint256)
```

## lockDiscountP

```solidity
function lockDiscountP(uint256 collatP, uint256 lockDuration) public view returns (uint256)
```

## totalSharesBeingWithdrawn

```solidity
function totalSharesBeingWithdrawn(address owner) public view returns (uint256 shares)
```

## tryUpdateCurrentMaxSupply

```solidity
function tryUpdateCurrentMaxSupply() public
```

## tryResetDailyAccPnlDelta

```solidity
function tryResetDailyAccPnlDelta() public
```

## tryNewOpenPnlRequestOrEpoch

```solidity
function tryNewOpenPnlRequestOrEpoch() public
```

## transfer

```solidity
function transfer(address to, uint256 amount) public returns (bool)
```

## transferFrom

```solidity
function transferFrom(address from, address to, uint256 amount) public returns (bool)
```

## decimals

```solidity
function decimals() public view returns (uint8)
```

## \_convertToShares

```solidity
function _convertToShares(uint256 assets, enum MathUpgradeable.Rounding rounding) internal view returns (uint256 shares)
```

*Internal conversion function (from assets to shares) with support for rounding direction.*

## \_convertToAssets

```solidity
function _convertToAssets(uint256 shares, enum MathUpgradeable.Rounding rounding) internal view returns (uint256 assets)
```

*Internal conversion function (from shares to assets) with support for rounding direction.*

## maxMint

```solidity
function maxMint(address) public view returns (uint256)
```

*See {IERC4626-maxMint}.*

## maxDeposit

```solidity
function maxDeposit(address owner) public view returns (uint256)
```

## maxRedeem

```solidity
function maxRedeem(address owner) public view returns (uint256)
```

*See {IERC4626-maxRedeem}.*

## maxWithdraw

```solidity
function maxWithdraw(address owner) public view returns (uint256)
```

*See {IERC4626-maxWithdraw}.*

## deposit

```solidity
function deposit(uint256 assets, address receiver) public returns (uint256)
```

*See {IERC4626-deposit}.*

## mint

```solidity
function mint(uint256 shares, address receiver) public returns (uint256)
```

\_See {IERC4626-mint}.

As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero. In this case, the shares will be minted without requiring any assets to be deposited.\_

## withdraw

```solidity
function withdraw(uint256 assets, address receiver, address owner) public returns (uint256)
```

*See {IERC4626-withdraw}.*

## redeem

```solidity
function redeem(uint256 shares, address receiver, address owner) public returns (uint256)
```

*See {IERC4626-redeem}.*

## makeWithdrawRequest

```solidity
function makeWithdrawRequest(uint256 shares, address owner) external
```

## cancelWithdrawRequest

```solidity
function cancelWithdrawRequest(uint256 shares, address owner, uint256 unlockEpoch) external
```

## depositWithDiscountAndLock

```solidity
function depositWithDiscountAndLock(uint256 assets, uint256 lockDuration, address receiver) external returns (uint256)
```

## mintWithDiscountAndLock

```solidity
function mintWithDiscountAndLock(uint256 shares, uint256 lockDuration, address receiver) external returns (uint256)
```

## unlockDeposit

```solidity
function unlockDeposit(uint256 depositId, address receiver) external
```

## distributeReward

```solidity
function distributeReward(uint256 assets) external
```

## sendAssets

```solidity
function sendAssets(uint256 assets, address receiver) external
```

## receiveAssets

```solidity
function receiveAssets(uint256 assets, address user) external
```

## deplete

```solidity
function deplete(uint256 assets) external
```

## refill

```solidity
function refill(uint256 assets) external
```

## updateAccPnlPerTokenUsed

```solidity
function updateAccPnlPerTokenUsed(uint256 prevPositiveOpenPnl, uint256 newPositiveOpenPnl) external returns (uint256)
```

## getLockedDeposit

```solidity
function getLockedDeposit(uint256 depositId) external view returns (struct IGToken.LockedDeposit)
```

## tvl

```solidity
function tvl() public view returns (uint256)
```

## availableAssets

```solidity
function availableAssets() public view returns (uint256)
```

## marketCap

```solidity
function marketCap() public view returns (uint256)
```


# GTokenOpenPnlFeed

*Manages open pnl oracle requests for a gToken vault*

## LINK\_FEE\_BALANCE\_DIVIDER

```solidity
uint256 LINK_FEE_BALANCE_DIVIDER
```

## MIN\_ANSWERS

```solidity
uint256 MIN_ANSWERS
```

## MIN\_REQUESTS\_START

```solidity
uint256 MIN_REQUESTS_START
```

## MAX\_REQUESTS\_START

```solidity
uint256 MAX_REQUESTS_START
```

## MIN\_REQUESTS\_EVERY

```solidity
uint256 MIN_REQUESTS_EVERY
```

## MAX\_REQUESTS\_EVERY

```solidity
uint256 MAX_REQUESTS_EVERY
```

## MIN\_REQUESTS\_COUNT

```solidity
uint256 MIN_REQUESTS_COUNT
```

## MAX\_REQUESTS\_COUNT

```solidity
uint256 MAX_REQUESTS_COUNT
```

## gToken

```solidity
contract IGToken gToken
```

## requestsStart

```solidity
uint256 requestsStart
```

## requestsEvery

```solidity
uint256 requestsEvery
```

## requestsCount

```solidity
uint256 requestsCount
```

## oracles

```solidity
address[] oracles
```

## job

```solidity
bytes32 job
```

## minAnswers

```solidity
uint256 minAnswers
```

## nextEpochValues

```solidity
int256[] nextEpochValues
```

## nextEpochValuesRequestCount

```solidity
uint256 nextEpochValuesRequestCount
```

## nextEpochValuesLastRequest

```solidity
uint256 nextEpochValuesLastRequest
```

## lastRequestId

```solidity
uint256 lastRequestId
```

## requestIds

```solidity
mapping(bytes32 => uint256) requestIds
```

## requests

```solidity
mapping(uint256 => struct IGTokenOpenPnlFeed.Request) requests
```

## requestAnswers

```solidity
mapping(uint256 => int256[]) requestAnswers
```

## constructor

```solidity
constructor(uint256 _LINK_FEE_BALANCE_DIVIDER, address _linkToken, contract IGToken _gToken, address[] _oracles, bytes32 _job, uint256 _minAnswers) public
```

## onlyGTokenOwner

```solidity
modifier onlyGTokenOwner()
```

## onlyGTokenManager

```solidity
modifier onlyGTokenManager()
```

## onlyGTokenAdmin

```solidity
modifier onlyGTokenAdmin()
```

## updateRequestsStart

```solidity
function updateRequestsStart(uint256 newValue) public
```

## updateRequestsEvery

```solidity
function updateRequestsEvery(uint256 newValue) public
```

## updateRequestsCount

```solidity
function updateRequestsCount(uint256 newValue) public
```

## updateRequestsInfoBatch

```solidity
function updateRequestsInfoBatch(uint256 newRequestsStart, uint256 newRequestsEvery, uint256 newRequestsCount) external
```

## updateMinAnswers

```solidity
function updateMinAnswers(uint256 newValue) external
```

## updateOracle

```solidity
function updateOracle(uint256 _index, address newValue) external
```

## updateOracles

```solidity
function updateOracles(address[] newValues) external
```

## updateJob

```solidity
function updateJob(bytes32 newValue) external
```

## resetNextEpochValueRequests

```solidity
function resetNextEpochValueRequests() external
```

## forceNewEpoch

```solidity
function forceNewEpoch() external
```

## newOpenPnlRequestOrEpoch

```solidity
function newOpenPnlRequestOrEpoch() external
```

## fulfill

```solidity
function fulfill(bytes32 requestId, int256 value) external
```


# Interfaces


# Libraries


# IBorrowingFeesUtils

*Interface for GNSBorrowingFees facet (inherits types and also contains functions, events, and custom errors)*

## setBorrowingPairParams

```solidity
function setBorrowingPairParams(uint8 _collateralIndex, uint16 _pairIndex, struct IBorrowingFees.BorrowingPairParams _value) external
```

*Updates borrowing pair params of a pair*

### Parameters

| Name              | Type                                                                                                                               | Description             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                              | index of the collateral |
| \_pairIndex       | uint16                                                                                                                             | index of the pair       |
| \_value           | [IBorrowingFees.BorrowingPairParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new value               |

## setBorrowingPairParamsArray

```solidity
function setBorrowingPairParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingPairParams[] _values) external
```

*Updates borrowing pair params of multiple pairs*

### Parameters

| Name              | Type                                                                                                                                   | Description             |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                                  | index of the collateral |
| \_indices         | uint16\[]                                                                                                                              | indices of the pairs    |
| \_values          | [IBorrowingFees.BorrowingPairParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingpairparams) | new values              |

## setBorrowingGroupParams

```solidity
function setBorrowingGroupParams(uint8 _collateralIndex, uint16 _groupIndex, struct IBorrowingFees.BorrowingGroupParams _value) external
```

*Updates borrowing group params of a group*

### Parameters

| Name              | Type                                                                                                                                 | Description                  |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| \_collateralIndex | uint8                                                                                                                                | index of the collateral      |
| \_groupIndex      | uint16                                                                                                                               | index of the borrowing group |
| \_value           | [IBorrowingFees.BorrowingGroupParams](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new value                    |

## setBorrowingGroupParamsArray

```solidity
function setBorrowingGroupParamsArray(uint8 _collateralIndex, uint16[] _indices, struct IBorrowingFees.BorrowingGroupParams[] _values) external
```

*Updates borrowing group params of multiple groups*

### Parameters

| Name              | Type                                                                                                                                     | Description             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| \_collateralIndex | uint8                                                                                                                                    | index of the collateral |
| \_indices         | uint16\[]                                                                                                                                | indices of the groups   |
| \_values          | [IBorrowingFees.BorrowingGroupParams\[\]](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowinggroupparams) | new values              |

## handleTradeBorrowingCallback

```solidity
function handleTradeBorrowingCallback(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, uint256 _positionSizeCollateral, bool _open, bool _long) external
```

*Callback after a trade is opened/closed to store pending borrowing fees and adjust open interests*

### Parameters

| Name                     | Type    | Description                                                   |
| ------------------------ | ------- | ------------------------------------------------------------- |
| \_collateralIndex        | uint8   | index of the collateral                                       |
| \_trader                 | address | address of the trader                                         |
| \_pairIndex              | uint16  | index of the pair                                             |
| \_index                  | uint32  | index of the trade                                            |
| \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens               |
| \_open                   | bool    | true if trade has been opened, false if trade has been closed |
| \_long                   | bool    | true if trade is long, false if trade is short                |

## resetTradeBorrowingFees

```solidity
function resetTradeBorrowingFees(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint32 _index, bool _long) external
```

*Resets a trade borrowing fee to 0 (useful when new trade opened or when partial trade executed)*

### Parameters

| Name              | Type    | Description                                    |
| ----------------- | ------- | ---------------------------------------------- |
| \_collateralIndex | uint8   | index of the collateral                        |
| \_trader          | address | address of the trader                          |
| \_pairIndex       | uint16  | index of the pair                              |
| \_index           | uint32  | index of the trade                             |
| \_long            | bool    | true if trade is long, false if trade is short |

## getBorrowingPairPendingAccFees

```solidity
function getBorrowingPairPendingAccFees(uint8 _collateralIndex, uint16 _pairIndex, uint256 _currentBlock) external view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 pairAccFeeDelta)
```

*Returns the pending acc borrowing fees for a pair on both sides*

### Parameters

| Name              | Type    | Description             |
| ----------------- | ------- | ----------------------- |
| \_collateralIndex | uint8   | index of the collateral |
| \_pairIndex       | uint16  | index of the pair       |
| \_currentBlock    | uint256 | current block number    |

### Return Values

| Name            | Type   | Description                                          |
| --------------- | ------ | ---------------------------------------------------- |
| accFeeLong      | uint64 | new pair acc borrowing fee on long side              |
| accFeeShort     | uint64 | new pair acc borrowing fee on short side             |
| pairAccFeeDelta | uint64 | pair acc borrowing fee delta (for side that changed) |

## getBorrowingGroupPendingAccFees

```solidity
function getBorrowingGroupPendingAccFees(uint8 _collateralIndex, uint16 _groupIndex, uint256 _currentBlock) external view returns (uint64 accFeeLong, uint64 accFeeShort, uint64 groupAccFeeDelta)
```

*Returns the pending acc borrowing fees for a borrowing group on both sides*

### Parameters

| Name              | Type    | Description                  |
| ----------------- | ------- | ---------------------------- |
| \_collateralIndex | uint8   | index of the collateral      |
| \_groupIndex      | uint16  | index of the borrowing group |
| \_currentBlock    | uint256 | current block number         |

### Return Values

| Name             | Type   | Description                                           |
| ---------------- | ------ | ----------------------------------------------------- |
| accFeeLong       | uint64 | new group acc borrowing fee on long side              |
| accFeeShort      | uint64 | new group acc borrowing fee on short side             |
| groupAccFeeDelta | uint64 | group acc borrowing fee delta (for side that changed) |

## getTradeBorrowingFee

```solidity
function getTradeBorrowingFee(struct IBorrowingFees.BorrowingFeeInput _input) external view returns (uint256 feeAmountCollateral)
```

*Returns the borrowing fee for a trade*

### Parameters

| Name    | Type                                                                                                                           | Description                                                                        |
| ------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| \_input | [IBorrowingFees.BorrowingFeeInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#borrowingfeeinput) | input data (collateralIndex, trader, pairIndex, index, long, collateral, leverage) |

### Return Values

| Name                | Type    | Description                          |
| ------------------- | ------- | ------------------------------------ |
| feeAmountCollateral | uint256 | borrowing fee (collateral precision) |

## getTradeLiquidationPrice

```solidity
function getTradeLiquidationPrice(struct IBorrowingFees.LiqPriceInput _input) external view returns (uint256)
```

*Returns the liquidation price for a trade*

### Parameters

| Name    | Type                                                                                                                   | Description                                                                                   |
| ------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| \_input | [IBorrowingFees.LiqPriceInput](/developer/technical-reference/contracts/interfaces/types/iborrowingfees#liqpriceinput) | input data (collateralIndex, trader, pairIndex, index, openPrice, long, collateral, leverage) |

## getPairOisCollateral

```solidity
function getPairOisCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256 longOi, uint256 shortOi)
```

*Returns the open interests for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

### Return Values

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| longOi  | uint256 | open interest on long side  |
| shortOi | uint256 | open interest on short side |

## getBorrowingPairGroupIndex

```solidity
function getBorrowingPairGroupIndex(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint16 groupIndex)
```

*Returns the borrowing group index for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

### Return Values

| Name       | Type   | Description           |
| ---------- | ------ | --------------------- |
| groupIndex | uint16 | borrowing group index |

## getPairOiCollateral

```solidity
function getPairOiCollateral(uint8 _collateralIndex, uint16 _pairIndex, bool _long) external view returns (uint256)
```

*Returns the open interest in collateral tokens for a pair on one side*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |
| \_long            | bool   | true if long side       |

## withinMaxBorrowingGroupOi

```solidity
function withinMaxBorrowingGroupOi(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateral) external view returns (bool)
```

*Returns whether a trade is within the max group borrowing open interest*

### Parameters

| Name                     | Type    | Description                                     |
| ------------------------ | ------- | ----------------------------------------------- |
| \_collateralIndex        | uint8   | index of the collateral                         |
| \_pairIndex              | uint16  | index of the pair                               |
| \_long                   | bool    | true if long side                               |
| \_positionSizeCollateral | uint256 | position size of the trade in collateral tokens |

## getBorrowingGroup

```solidity
function getBorrowingGroup(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.BorrowingData group)
```

*Returns a borrowing group's data*

### Parameters

| Name              | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| \_collateralIndex | uint8  | index of the collateral      |
| \_groupIndex      | uint16 | index of the borrowing group |

## getBorrowingGroupOi

```solidity
function getBorrowingGroupOi(uint8 _collateralIndex, uint16 _groupIndex) external view returns (struct IBorrowingFees.OpenInterest group)
```

*Returns a borrowing group's oi data*

### Parameters

| Name              | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| \_collateralIndex | uint8  | index of the collateral      |
| \_groupIndex      | uint16 | index of the borrowing group |

## getBorrowingPair

```solidity
function getBorrowingPair(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingData)
```

*Returns a borrowing pair's data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getBorrowingPairOi

```solidity
function getBorrowingPairOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.OpenInterest)
```

*Returns a borrowing pair's oi data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getBorrowingPairGroups

```solidity
function getBorrowingPairGroups(uint8 _collateralIndex, uint16 _pairIndex) external view returns (struct IBorrowingFees.BorrowingPairGroup[])
```

*Returns a borrowing pair's oi data*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getAllBorrowingPairs

```solidity
function getAllBorrowingPairs(uint8 _collateralIndex) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[], struct IBorrowingFees.BorrowingPairGroup[][])
```

*Returns all borrowing pairs' borrowing data, oi data, and pair groups data*

### Parameters

| Name              | Type  | Description             |
| ----------------- | ----- | ----------------------- |
| \_collateralIndex | uint8 | index of the collateral |

## getBorrowingGroups

```solidity
function getBorrowingGroups(uint8 _collateralIndex, uint16[] _indices) external view returns (struct IBorrowingFees.BorrowingData[], struct IBorrowingFees.OpenInterest[])
```

*Returns borrowing groups' data and oi data*

### Parameters

| Name              | Type      | Description             |
| ----------------- | --------- | ----------------------- |
| \_collateralIndex | uint8     | index of the collateral |
| \_indices         | uint16\[] | indices of the groups   |

## getBorrowingInitialAccFees

```solidity
function getBorrowingInitialAccFees(uint8 _collateralIndex, address _trader, uint32 _index) external view returns (struct IBorrowingFees.BorrowingInitialAccFees)
```

*Returns borrowing groups' data*

### Parameters

| Name              | Type    | Description             |
| ----------------- | ------- | ----------------------- |
| \_collateralIndex | uint8   | index of the collateral |
| \_trader          | address | address of trader       |
| \_index           | uint32  | index of trade          |

## getPairMaxOi

```solidity
function getPairMaxOi(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256)
```

*Returns the max open interest for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## getPairMaxOiCollateral

```solidity
function getPairMaxOiCollateral(uint8 _collateralIndex, uint16 _pairIndex) external view returns (uint256)
```

*Returns the max open interest in collateral tokens for a pair*

### Parameters

| Name              | Type   | Description             |
| ----------------- | ------ | ----------------------- |
| \_collateralIndex | uint8  | index of the collateral |
| \_pairIndex       | uint16 | index of the pair       |

## BorrowingPairParamsUpdated

```solidity
event BorrowingPairParamsUpdated(uint8 collateralIndex, uint16 pairIndex, uint16 groupIndex, uint32 feePerBlock, uint48 feeExponent, uint72 maxOi)
```

*Emitted when a pair's borrowing params is updated*

### Parameters

| Name            | Type   | Description            |
| --------------- | ------ | ---------------------- |
| collateralIndex | uint8  |                        |
| pairIndex       | uint16 | index of the pair      |
| groupIndex      | uint16 | index of its new group |
| feePerBlock     | uint32 | new fee per block      |
| feeExponent     | uint48 | new fee exponent       |
| maxOi           | uint72 | new max open interest  |

## BorrowingPairGroupUpdated

```solidity
event BorrowingPairGroupUpdated(uint8 collateralIndex, uint16 pairIndex, uint16 prevGroupIndex, uint16 newGroupIndex)
```

*Emitted when a pair's borrowing group has been updated*

### Parameters

| Name            | Type   | Description                    |
| --------------- | ------ | ------------------------------ |
| collateralIndex | uint8  |                                |
| pairIndex       | uint16 | index of the pair              |
| prevGroupIndex  | uint16 | previous borrowing group index |
| newGroupIndex   | uint16 | new borrowing group index      |

## BorrowingGroupUpdated

```solidity
event BorrowingGroupUpdated(uint8 collateralIndex, uint16 groupIndex, uint32 feePerBlock, uint72 maxOi, uint48 feeExponent)
```

*Emitted when a group's borrowing params is updated*

### Parameters

| Name            | Type   | Description           |
| --------------- | ------ | --------------------- |
| collateralIndex | uint8  |                       |
| groupIndex      | uint16 | index of the group    |
| feePerBlock     | uint32 | new fee per block     |
| maxOi           | uint72 | new max open interest |
| feeExponent     | uint48 | new fee exponent      |

## BorrowingInitialAccFeesStored

```solidity
event BorrowingInitialAccFeesStored(uint8 collateralIndex, address trader, uint16 pairIndex, uint32 index, bool long, uint64 initialPairAccFee, uint64 initialGroupAccFee)
```

*Emitted when a trade's initial acc borrowing fees are stored*

### Parameters

| Name               | Type    | Description                                       |
| ------------------ | ------- | ------------------------------------------------- |
| collateralIndex    | uint8   |                                                   |
| trader             | address | address of the trader                             |
| pairIndex          | uint16  | index of the pair                                 |
| index              | uint32  | index of the trade                                |
| long               | bool    |                                                   |
| initialPairAccFee  | uint64  | initial pair acc fee (for the side of the trade)  |
| initialGroupAccFee | uint64  | initial group acc fee (for the side of the trade) |

## TradeBorrowingCallbackHandled

```solidity
event TradeBorrowingCallbackHandled(uint8 collateralIndex, address trader, uint16 pairIndex, uint32 index, bool open, bool long, uint256 positionSizeCollateral)
```

*Emitted when a trade is executed and borrowing callback is handled*

### Parameters

| Name                   | Type    | Description                                                   |
| ---------------------- | ------- | ------------------------------------------------------------- |
| collateralIndex        | uint8   |                                                               |
| trader                 | address | address of the trader                                         |
| pairIndex              | uint16  | index of the pair                                             |
| index                  | uint32  | index of the trade                                            |
| open                   | bool    | true if trade has been opened, false if trade has been closed |
| long                   | bool    | true if trade is long, false if trade is short                |
| positionSizeCollateral | uint256 | position size of the trade in collateral tokens               |

## BorrowingPairAccFeesUpdated

```solidity
event BorrowingPairAccFeesUpdated(uint8 collateralIndex, uint16 pairIndex, uint256 currentBlock, uint64 accFeeLong, uint64 accFeeShort)
```

*Emitted when a pair's borrowing acc fees are updated*

### Parameters

| Name            | Type    | Description                              |
| --------------- | ------- | ---------------------------------------- |
| collateralIndex | uint8   |                                          |
| pairIndex       | uint16  | index of the pair                        |
| currentBlock    | uint256 | current block number                     |
| accFeeLong      | uint64  | new pair acc borrowing fee on long side  |
| accFeeShort     | uint64  | new pair acc borrowing fee on short side |

## BorrowingGroupAccFeesUpdated

```solidity
event BorrowingGroupAccFeesUpdated(uint8 collateralIndex, uint16 groupIndex, uint256 currentBlock, uint64 accFeeLong, uint64 accFeeShort)
```

*Emitted when a group's borrowing acc fees are updated*

### Parameters

| Name            | Type    | Description                               |
| --------------- | ------- | ----------------------------------------- |
| collateralIndex | uint8   |                                           |
| groupIndex      | uint16  | index of the borrowing group              |
| currentBlock    | uint256 | current block number                      |
| accFeeLong      | uint64  | new group acc borrowing fee on long side  |
| accFeeShort     | uint64  | new group acc borrowing fee on short side |

## BorrowingPairOiUpdated

```solidity
event BorrowingPairOiUpdated(uint8 collateralIndex, uint16 pairIndex, bool long, bool increase, uint72 delta, uint72 newOiLong, uint72 newOiShort)
```

*Emitted when a borrowing pair's open interests are updated*

### Parameters

| Name            | Type   | Description                                                   |
| --------------- | ------ | ------------------------------------------------------------- |
| collateralIndex | uint8  |                                                               |
| pairIndex       | uint16 | index of the pair                                             |
| long            | bool   | true if long side                                             |
| increase        | bool   | true if open interest is increased, false if decreased        |
| delta           | uint72 | change in open interest in collateral tokens (1e10 precision) |
| newOiLong       | uint72 | new open interest on long side                                |
| newOiShort      | uint72 | new open interest on short side                               |

## BorrowingGroupOiUpdated

```solidity
event BorrowingGroupOiUpdated(uint8 collateralIndex, uint16 groupIndex, bool long, bool increase, uint72 delta, uint72 newOiLong, uint72 newOiShort)
```

*Emitted when a borrowing group's open interests are updated*

### Parameters

| Name            | Type   | Description                                                   |
| --------------- | ------ | ------------------------------------------------------------- |
| collateralIndex | uint8  |                                                               |
| groupIndex      | uint16 | index of the borrowing group                                  |
| long            | bool   | true if long side                                             |
| increase        | bool   | true if open interest is increased, false if decreased        |
| delta           | uint72 | change in open interest in collateral tokens (1e10 precision) |
| newOiLong       | uint72 | new open interest on long side                                |
| newOiShort      | uint72 | new open interest on short side                               |

## BorrowingZeroGroup

```solidity
error BorrowingZeroGroup()
```

## BorrowingWrongExponent

```solidity
error BorrowingWrongExponent()
```


# IOtcUtils

*Interface for GNSOtc facet (inherits types and also contains functions, events, and custom errors)*

## initializeOtc

```solidity
function initializeOtc(struct IOtc.OtcConfig _config) external
```

*Initializer for OTC facet*

### Parameters

| Name     | Type                                                                                       | Description    |
| -------- | ------------------------------------------------------------------------------------------ | -------------- |
| \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config |

## updateOtcConfig

```solidity
function updateOtcConfig(struct IOtc.OtcConfig _config) external
```

*Updates OTC config*

### Parameters

| Name     | Type                                                                                       | Description                                                                                                                                        |
| -------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| \_config | [IOtc.OtcConfig](/developer/technical-reference/contracts/interfaces/types/iotc#otcconfig) | new OTC Config. Sum of `treasuryShareP`, `stakingShareP`, `burnShareP` must equal 100 and `premiumP` must be less than or equal to MAX\_PREMIUM\_P |

## addOtcCollateralBalance

```solidity
function addOtcCollateralBalance(uint8 _collateralIndex, uint256 _collateralAmount) external
```

*Increases OTC balance for a collateral*

### Parameters

| Name               | Type    | Description                                             |
| ------------------ | ------- | ------------------------------------------------------- |
| \_collateralIndex  | uint8   | collateral index                                        |
| \_collateralAmount | uint256 | amount of collateral to increase (collateral precision) |

## sellGnsForCollateral

```solidity
function sellGnsForCollateral(uint8 _collateralIndex, uint256 _collateralAmount) external
```

*OTC Buys GNS from caller for `_amountCollateral` of `_collateralIndex`*

### Parameters

| Name               | Type    | Description                                          |
| ------------------ | ------- | ---------------------------------------------------- |
| \_collateralIndex  | uint8   | collateral index                                     |
| \_collateralAmount | uint256 | amount of collateral to trade (collateral precision) |

## getOtcConfig

```solidity
function getOtcConfig() external view returns (struct IOtc.OtcConfig)
```

*Returns OTC Config*

## getOtcBalance

```solidity
function getOtcBalance(uint8 _collateralIndex) external view returns (uint256)
```

*Returns OTC balance for a collateral (collateral precision)*

### Parameters

| Name              | Type  | Description      |
| ----------------- | ----- | ---------------- |
| \_collateralIndex | uint8 | collateral index |

## getOtcRate

```solidity
function getOtcRate(uint8 _collateralIndex) external view returns (uint256)
```

*Returns OTC rate (price + premium) of GNS in collateral (1e10)*

### Parameters

| Name              | Type  | Description      |
| ----------------- | ----- | ---------------- |
| \_collateralIndex | uint8 | collateral index |

## OtcConfigUpdated

```solidity
event OtcConfigUpdated(struct IOtc.OtcConfig config)
```

*Emitted when OTCConfig is updated*

### Parameters

| Name   | Type                  | Description    |
| ------ | --------------------- | -------------- |
| config | struct IOtc.OtcConfig | new OTC config |

## OtcBalanceUpdated

```solidity
event OtcBalanceUpdated(uint8 collateralIndex, uint256 balanceCollateral)
```

*Emitted when OTC balance is updated*

### Parameters

| Name              | Type    | Description                        |
| ----------------- | ------- | ---------------------------------- |
| collateralIndex   | uint8   | collateral index                   |
| balanceCollateral | uint256 | new balance (collateral precision) |

## OtcExecuted

```solidity
event OtcExecuted(uint8 collateralIndex, uint256 collateralAmount, uint256 gnsPriceCollateral, uint256 treasuryAmountGns, uint256 stakingAmountGns, uint256 burnAmountGns)
```

*Emitted when an OTC trade is executed*

### Parameters

| Name               | Type    | Description                                              |
| ------------------ | ------- | -------------------------------------------------------- |
| collateralIndex    | uint8   | collateral index                                         |
| collateralAmount   | uint256 | amount of collateral traded (collateral precision)       |
| gnsPriceCollateral | uint256 | effective gns/collateral price, including premium (1e10) |
| treasuryAmountGns  | uint256 | amount of GNS sent to treasury (1e18)                    |
| stakingAmountGns   | uint256 | amount of GNS sent to GNS Staking (1e18)                 |
| burnAmountGns      | uint256 | amount of GNS burned (1e18)                              |

## InvalidShareSum

```solidity
error InvalidShareSum()
```


# IPriceAggregatorUtils

*Interface for GNSPriceAggregator facet (inherits types and also contains functions, events, and custom errors)*

## initializePriceAggregator

```solidity
function initializePriceAggregator(address _linkToken, contract IChainlinkFeed _linkUsdPriceFeed, uint24 _twapInterval, uint8 _minAnswers, address[] _oracles, bytes32[2] _jobIds, uint8[] _collateralIndices, struct IPriceAggregator.LiquidityPoolInput[] _gnsCollateralLiquidityPools, contract IChainlinkFeed[] _collateralUsdPriceFeeds) external
```

*Initializes price aggregator facet*

### Parameters

| Name                          | Type                                                                                                                                     | Description                                            |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| \_linkToken                   | address                                                                                                                                  | LINK token address                                     |
| \_linkUsdPriceFeed            | contract IChainlinkFeed                                                                                                                  | LINK/USD price feed address                            |
| \_twapInterval                | uint24                                                                                                                                   | TWAP interval (seconds)                                |
| \_minAnswers                  | uint8                                                                                                                                    | answers count at which a trade is executed with median |
| \_oracles                     | address\[]                                                                                                                               | chainlink oracle addresses                             |
| \_jobIds                      | bytes32\[2]                                                                                                                              | chainlink job ids (market/lookback)                    |
| \_collateralIndices           | uint8\[]                                                                                                                                 | collateral indices                                     |
| \_gnsCollateralLiquidityPools | [IPriceAggregator.LiquidityPoolInput\[\]](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | corresponding GNS/collateral liquidity pool values     |
| \_collateralUsdPriceFeeds     | contract IChainlinkFeed\[]                                                                                                               | corresponding collateral/USD chainlink price feeds     |

## updateLinkUsdPriceFeed

```solidity
function updateLinkUsdPriceFeed(contract IChainlinkFeed _value) external
```

*Updates LINK/USD chainlink price feed*

### Parameters

| Name    | Type                    | Description |
| ------- | ----------------------- | ----------- |
| \_value | contract IChainlinkFeed | new value   |

## updateCollateralUsdPriceFeed

```solidity
function updateCollateralUsdPriceFeed(uint8 _collateralIndex, contract IChainlinkFeed _value) external
```

*Updates collateral/USD chainlink price feed*

### Parameters

| Name              | Type                    | Description      |
| ----------------- | ----------------------- | ---------------- |
| \_collateralIndex | uint8                   | collateral index |
| \_value           | contract IChainlinkFeed | new value        |

## updateCollateralGnsLiquidityPool

```solidity
function updateCollateralGnsLiquidityPool(uint8 _collateralIndex, struct IPriceAggregator.LiquidityPoolInput _liquidityPoolInput) external
```

*Updates collateral/GNS liquidity pool*

### Parameters

| Name                 | Type                                                                                                                                 | Description      |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------- |
| \_collateralIndex    | uint8                                                                                                                                | collateral index |
| \_liquidityPoolInput | [IPriceAggregator.LiquidityPoolInput](/developer/technical-reference/contracts/interfaces/types/ipriceaggregator#liquiditypoolinput) | new values       |

## updateTwapInterval

```solidity
function updateTwapInterval(uint24 _twapInterval) external
```

*Updates TWAP interval*

### Parameters

| Name           | Type   | Description         |
| -------------- | ------ | ------------------- |
| \_twapInterval | uint24 | new value (seconds) |

## updateMinAnswers

```solidity
function updateMinAnswers(uint8 _value) external
```

*Updates minimum answers count*

### Parameters

| Name    | Type  | Description |
| ------- | ----- | ----------- |
| \_value | uint8 | new value   |

## addOracle

```solidity
function addOracle(address _a) external
```

*Adds an oracle*

### Parameters

| Name | Type    | Description |
| ---- | ------- | ----------- |
| \_a  | address | new value   |

## replaceOracle

```solidity
function replaceOracle(uint256 _index, address _a) external
```

*Replaces an oracle*

### Parameters

| Name    | Type    | Description  |
| ------- | ------- | ------------ |
| \_index | uint256 | oracle index |
| \_a     | address | new value    |

## removeOracle

```solidity
function removeOracle(uint256 _index) external
```

*Removes an oracle*

### Parameters

| Name    | Type    | Description  |
| ------- | ------- | ------------ |
| \_index | uint256 | oracle index |

## setMarketJobId

```solidity
function setMarketJobId(bytes32 _jobId) external
```

*Updates market job id*

### Parameters

| Name    | Type    | Description |
| ------- | ------- | ----------- |
| \_jobId | bytes32 | new value   |

## setLimitJobId

```solidity
function setLimitJobId(bytes32 _jobId) external
```

*Updates lookback job id*

### Parameters

| Name    | Type    | Description |
| ------- | ------- | ----------- |
| \_jobId | bytes32 | new value   |

## getPrice

```solidity
function getPrice(uint8 _collateralIndex, uint16 _pairIndex, struct ITradingStorage.Id _tradeId, struct ITradingStorage.Id _orderId, enum ITradingStorage.PendingOrderType _orderType, uint256 _positionSizeCollateral, uint256 _fromBlock) external
```

*Requests price from oracles*

### Parameters

| Name                     | Type                                                                                               | Description                                                      |
| ------------------------ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| \_collateralIndex        | uint8                                                                                              | collateral index                                                 |
| \_pairIndex              | uint16                                                                                             | pair index                                                       |
| \_tradeId                | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | trade id                                                         |
| \_orderId                | [ITradingStorage.Id](/developer/technical-reference/contracts/interfaces/types/itradingstorage#id) | order id                                                         |
| \_orderType              | enum ITradingStorage.PendingOrderType                                                              | order type                                                       |
| \_positionSizeCollateral | uint256                                                                                            | position size (collateral precision)                             |
| \_fromBlock              | uint256                                                                                            | block number from which to start fetching prices (for lookbacks) |

## fulfill

```solidity
function fulfill(bytes32 _requestId, uint256 _priceData) external
```

*Fulfills price request, called by chainlink oracles*

### Parameters

| Name        | Type    | Description |
| ----------- | ------- | ----------- |
| \_requestId | bytes32 | request id  |
| \_priceData | uint256 | price data  |

## claimBackLink

```solidity
function claimBackLink() external
```

*Claims back LINK tokens, called by gov fund*

## getLinkFee

```solidity
function getLinkFee(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) external view returns (uint256)
```

*Returns LINK fee for price request*

### Parameters

| Name                     | Type    | Description                                               |
| ------------------------ | ------- | --------------------------------------------------------- |
| \_collateralIndex        | uint8   | collateral index                                          |
| \_trader                 | address | trader address                                            |
| \_pairIndex              | uint16  | pair index                                                |
| \_positionSizeCollateral | uint256 | position size in collateral tokens (collateral precision) |

## getCollateralPriceUsd

```solidity
function getCollateralPriceUsd(uint8 _collateralIndex) external view returns (uint256)
```

*Returns collateral/USD price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getUsdNormalizedValue

```solidity
function getUsdNormalizedValue(uint8 _collateralIndex, uint256 _collateralValue) external view returns (uint256)
```

*Returns USD normalized value from collateral value*

### Parameters

| Name              | Type    | Description                             |
| ----------------- | ------- | --------------------------------------- |
| \_collateralIndex | uint8   | index of collateral                     |
| \_collateralValue | uint256 | collateral value (collateral precision) |

## getCollateralFromUsdNormalizedValue

```solidity
function getCollateralFromUsdNormalizedValue(uint8 _collateralIndex, uint256 _normalizedValue) external view returns (uint256)
```

*Returns collateral value (collateral precision) from USD normalized value*

### Parameters

| Name              | Type    | Description                 |
| ----------------- | ------- | --------------------------- |
| \_collateralIndex | uint8   | index of collateral         |
| \_normalizedValue | uint256 | normalized value (1e18 USD) |

## getGnsPriceUsd

```solidity
function getGnsPriceUsd(uint8 _collateralIndex) external view returns (uint256)
```

*Returns GNS/USD price based on GNS/collateral price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getGnsPriceUsd

```solidity
function getGnsPriceUsd(uint8 _collateralIndex, uint256 _gnsPriceCollateral) external view returns (uint256)
```

*Returns GNS/USD price based on GNS/collateral price*

### Parameters

| Name                 | Type    | Description                 |
| -------------------- | ------- | --------------------------- |
| \_collateralIndex    | uint8   | index of collateral         |
| \_gnsPriceCollateral | uint256 | GNS/collateral price (1e10) |

## getGnsPriceCollateralIndex

```solidity
function getGnsPriceCollateralIndex(uint8 _collateralIndex) external view returns (uint256)
```

*Returns GNS/collateral price*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getGnsPriceCollateralAddress

```solidity
function getGnsPriceCollateralAddress(address _collateral) external view returns (uint256)
```

*Returns GNS/collateral price*

### Parameters

| Name         | Type    | Description               |
| ------------ | ------- | ------------------------- |
| \_collateral | address | address of the collateral |

## getLinkUsdPriceFeed

```solidity
function getLinkUsdPriceFeed() external view returns (contract IChainlinkFeed)
```

*Returns the link/usd price feed address*

## getTwapInterval

```solidity
function getTwapInterval() external view returns (uint24)
```

*Returns the twap interval in seconds*

## getMinAnswers

```solidity
function getMinAnswers() external view returns (uint8)
```

*Returns the minimum answers to execute an order and take the median*

## getMarketJobId

```solidity
function getMarketJobId() external view returns (bytes32)
```

*Returns the market job id*

## getLimitJobId

```solidity
function getLimitJobId() external view returns (bytes32)
```

*Returns the limit job id*

## getOracle

```solidity
function getOracle(uint256 _index) external view returns (address)
```

*Returns a specific oracle*

### Parameters

| Name    | Type    | Description         |
| ------- | ------- | ------------------- |
| \_index | uint256 | index of the oracle |

## getOracles

```solidity
function getOracles() external view returns (address[])
```

*Returns all oracles*

## getCollateralGnsLiquidityPool

```solidity
function getCollateralGnsLiquidityPool(uint8 _collateralIndex) external view returns (struct IPriceAggregator.LiquidityPoolInfo)
```

*Returns collateral/gns liquidity pool info*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getCollateralUsdPriceFeed

```solidity
function getCollateralUsdPriceFeed(uint8 _collateralIndex) external view returns (contract IChainlinkFeed)
```

*Returns collateral/usd chainlink price feed*

### Parameters

| Name              | Type  | Description         |
| ----------------- | ----- | ------------------- |
| \_collateralIndex | uint8 | index of collateral |

## getPriceAggregatorOrder

```solidity
function getPriceAggregatorOrder(bytes32 _requestId) external view returns (struct IPriceAggregator.Order)
```

*Returns order data*

### Parameters

| Name        | Type    | Description         |
| ----------- | ------- | ------------------- |
| \_requestId | bytes32 | index of collateral |

## getPriceAggregatorOrderAnswers

```solidity
function getPriceAggregatorOrderAnswers(struct ITradingStorage.Id _orderId) external view returns (struct IPriceAggregator.OrderAnswer[])
```

*Returns order data*

### Parameters

| Name      | Type               | Description |
| --------- | ------------------ | ----------- |
| \_orderId | ITradingStorage.Id | order id    |

## getChainlinkToken

```solidity
function getChainlinkToken() external view returns (address)
```

*Returns chainlink token address*

## getRequestCount

```solidity
function getRequestCount() external view returns (uint256)
```

*Returns requestCount (used by ChainlinkClientUtils)*

## getPendingRequest

```solidity
function getPendingRequest(bytes32 _id) external view returns (address)
```

*Returns pendingRequests mapping entry (used by ChainlinkClientUtils)*

## LinkUsdPriceFeedUpdated

```solidity
event LinkUsdPriceFeedUpdated(address value)
```

*Emitted when LINK/USD price feed is updated*

### Parameters

| Name  | Type    | Description |
| ----- | ------- | ----------- |
| value | address | new value   |

## CollateralUsdPriceFeedUpdated

```solidity
event CollateralUsdPriceFeedUpdated(uint8 collateralIndex, address value)
```

*Emitted when collateral/USD price feed is updated*

### Parameters

| Name            | Type    | Description      |
| --------------- | ------- | ---------------- |
| collateralIndex | uint8   | collateral index |
| value           | address | new value        |

## CollateralGnsLiquidityPoolUpdated

```solidity
event CollateralGnsLiquidityPoolUpdated(uint8 collateralIndex, struct IPriceAggregator.LiquidityPoolInfo newValue)
```

*Emitted when collateral/GNS Uniswap V3 pool is updated*

### Parameters

| Name            | Type                                      | Description      |
| --------------- | ----------------------------------------- | ---------------- |
| collateralIndex | uint8                                     | collateral index |
| newValue        | struct IPriceAggregator.LiquidityPoolInfo | new value        |

## TwapIntervalUpdated

```solidity
event TwapIntervalUpdated(uint32 newValue)
```

*Emitted when TWAP interval is updated*

### Parameters

| Name     | Type   | Description |
| -------- | ------ | ----------- |
| newValue | uint32 | new value   |

## MinAnswersUpdated

```solidity
event MinAnswersUpdated(uint8 value)
```

*Emitted when minimum answers count is updated*

### Parameters

| Name  | Type  | Description |
| ----- | ----- | ----------- |
| value | uint8 | new value   |

## OracleAdded

```solidity
event OracleAdded(uint256 index, address value)
```

*Emitted when an oracle is added*

### Parameters

| Name  | Type    | Description      |
| ----- | ------- | ---------------- |
| index | uint256 | new oracle index |
| value | address | value            |

## OracleReplaced

```solidity
event OracleReplaced(uint256 index, address oldOracle, address newOracle)
```

*Emitted when an oracle is replaced*

### Parameters

| Name      | Type    | Description  |
| --------- | ------- | ------------ |
| index     | uint256 | oracle index |
| oldOracle | address | old value    |
| newOracle | address | new value    |

## OracleRemoved

```solidity
event OracleRemoved(uint256 index, address oldOracle)
```

*Emitted when an oracle is removed*

### Parameters

| Name      | Type    | Description  |
| --------- | ------- | ------------ |
| index     | uint256 | oracle index |
| oldOracle | address | old value    |

## JobIdUpdated

```solidity
event JobIdUpdated(uint256 index, bytes32 jobId)
```

*Emitted when market job id is updated*

### Parameters

| Name  | Type    | Description |
| ----- | ------- | ----------- |
| index | uint256 | index       |
| jobId | bytes32 | new value   |

## LinkRequestCreated

```solidity
event LinkRequestCreated(struct Chainlink.Request request)
```

*Emitted when a chainlink request is created*

### Parameters

| Name    | Type                     | Description          |
| ------- | ------------------------ | -------------------- |
| request | struct Chainlink.Request | link request details |

## PriceRequested

```solidity
event PriceRequested(uint8 collateralIndex, uint256 pairIndex, struct ITradingStorage.Id tradeId, struct ITradingStorage.Id pendingOrderId, enum ITradingStorage.PendingOrderType orderType, uint256 fromBlock, bool isLookback, bytes32 job, uint256 linkFeePerNode, uint256 nodesCount)
```

*Emitted when a price is requested to the oracles*

### Parameters

| Name            | Type                                  | Description                                                      |
| --------------- | ------------------------------------- | ---------------------------------------------------------------- |
| collateralIndex | uint8                                 | collateral index                                                 |
| pairIndex       | uint256                               | trading pair index                                               |
| tradeId         | struct ITradingStorage.Id             | trader id                                                        |
| pendingOrderId  | struct ITradingStorage.Id             | pending order id                                                 |
| orderType       | enum ITradingStorage.PendingOrderType | order type (market open/market close/limit open/stop open/etc.)  |
| fromBlock       | uint256                               | block number from which to start fetching prices (for lookbacks) |
| isLookback      | bool                                  | true if lookback                                                 |
| job             | bytes32                               | chainlink job id (market/lookback)                               |
| linkFeePerNode  | uint256                               | link fee distributed per node (1e18 precision)                   |
| nodesCount      | uint256                               | amount of nodes to fetch prices from                             |

## TradingCallbackExecuted

```solidity
event TradingCallbackExecuted(struct ITradingCallbacks.AggregatorAnswer a, enum ITradingStorage.PendingOrderType orderType)
```

*Emitted when a trading callback is called from the price aggregator*

### Parameters

| Name      | Type                                      | Description            |
| --------- | ----------------------------------------- | ---------------------- |
| a         | struct ITradingCallbacks.AggregatorAnswer | aggregator answer data |
| orderType | enum ITradingStorage.PendingOrderType     | order type             |

## PriceReceived

```solidity
event PriceReceived(struct ITradingStorage.Id orderId, uint16 pairIndex, bytes32 request, uint256 priceData, bool isLookback, bool usedInMedian)
```

*Emitted when a price is received from the oracles*

### Parameters

| Name         | Type                      | Description                                                                   |
| ------------ | ------------------------- | ----------------------------------------------------------------------------- |
| orderId      | struct ITradingStorage.Id | pending order id                                                              |
| pairIndex    | uint16                    | trading pair index                                                            |
| request      | bytes32                   | chainlink request id                                                          |
| priceData    | uint256                   | OrderAnswer compressed into uint256                                           |
| isLookback   | bool                      | true if lookback                                                              |
| usedInMedian | bool                      | false if order already executed because min answers count was already reached |

## LinkClaimedBack

```solidity
event LinkClaimedBack(uint256 amountLink)
```

*Emitted when LINK tokens are claimed back by gov fund*

### Parameters

| Name       | Type    | Description                        |
| ---------- | ------- | ---------------------------------- |
| amountLink | uint256 | amount of LINK tokens claimed back |

## TransferAndCallToOracleFailed

```solidity
error TransferAndCallToOracleFailed()
```

## SourceNotOracleOfRequest

```solidity
error SourceNotOracleOfRequest()
```

## RequestAlreadyPending

```solidity
error RequestAlreadyPending()
```

## OracleAlreadyListed

```solidity
error OracleAlreadyListed()
```

## InvalidCandle

```solidity
error InvalidCandle()
```

## WrongCollateralUsdDecimals

```solidity
error WrongCollateralUsdDecimals()
```

## InvalidPoolType

```solidity
error InvalidPoolType()
```


# ITriggerRewardsUtils

*Interface for GNSTriggerRewards facet (inherits types and also contains functions, events, and custom errors)*

## initializeTriggerRewards

```solidity
function initializeTriggerRewards(uint16 _timeoutBlocks) external
```

*Initializes parameters for trigger rewards facet*

### Parameters

| Name            | Type   | Description                            |
| --------------- | ------ | -------------------------------------- |
| \_timeoutBlocks | uint16 | blocks after which a trigger times out |

## updateTriggerTimeoutBlocks

```solidity
function updateTriggerTimeoutBlocks(uint16 _timeoutBlocks) external
```

*Updates the blocks after which a trigger times out*

### Parameters

| Name            | Type   | Description                            |
| --------------- | ------ | -------------------------------------- |
| \_timeoutBlocks | uint16 | blocks after which a trigger times out |

## distributeTriggerReward

```solidity
function distributeTriggerReward(uint256 _rewardGns) external
```

*Distributes GNS rewards to oracles for a specific trigger*

### Parameters

| Name        | Type    | Description                                      |
| ----------- | ------- | ------------------------------------------------ |
| \_rewardGns | uint256 | total GNS reward to be distributed among oracles |

## claimPendingTriggerRewards

```solidity
function claimPendingTriggerRewards(address _oracle) external
```

*Claims pending GNS trigger rewards for the caller*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_oracle | address | address of the oracle |

## getTriggerTimeoutBlocks

```solidity
function getTriggerTimeoutBlocks() external view returns (uint16)
```

*Returns current triggerTimeoutBlocks value*

## hasActiveOrder

```solidity
function hasActiveOrder(uint256 _orderBlock) external view returns (bool)
```

*Checks if an order is active (exists and has not timed out)*

### Parameters

| Name         | Type    | Description               |
| ------------ | ------- | ------------------------- |
| \_orderBlock | uint256 | block number of the order |

## getTriggerPendingRewardsGns

```solidity
function getTriggerPendingRewardsGns(address _oracle) external view returns (uint256)
```

*Returns the pending GNS trigger rewards for an oracle*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_oracle | address | address of the oracle |

## TriggerTimeoutBlocksUpdated

```solidity
event TriggerTimeoutBlocksUpdated(uint16 timeoutBlocks)
```

*Emitted when timeoutBlocks is updated*

### Parameters

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| timeoutBlocks | uint16 | blocks after which a trigger times out |

## TriggerRewarded

```solidity
event TriggerRewarded(uint256 rewardsPerOracleGns, uint256 oraclesCount)
```

*Emitted when trigger rewards are distributed for a specific order*

### Parameters

| Name                | Type    | Description                          |
| ------------------- | ------- | ------------------------------------ |
| rewardsPerOracleGns | uint256 | reward in GNS distributed per oracle |
| oraclesCount        | uint256 | number of oracles rewarded           |

## TriggerRewardsClaimed

```solidity
event TriggerRewardsClaimed(address oracle, uint256 rewardsGns)
```

*Emitted when pending GNS trigger rewards are claimed by an oracle*

### Parameters

| Name       | Type    | Description           |
| ---------- | ------- | --------------------- |
| oracle     | address | address of the oracle |
| rewardsGns | uint256 | GNS rewards claimed   |

## TimeoutBlocksZero

```solidity
error TimeoutBlocksZero()
```

## NoPendingTriggerRewards

```solidity
error NoPendingTriggerRewards()
```




---

[Next Page](/llms-full.txt/1)

