Gains Network
  • 📚Home
  • Gains Network
    • 🔎Overview
    • 🍏GNS Token
    • 📔Contract Addresses
      • Apechain Mainnet
      • Arbitrum Mainnet
      • Base Mainnet
      • Polygon Mainnet
  • gTrade (Leveraged Trading)
    • 🔎Overview
    • 🎛️Setting up to trade
      • 🟣Polygon Network Setup
      • 🔵Arbitrum Network Setup
    • 🏦Opening / Closing trades
    • 💲Trade Collaterals
      • Spotlight: WETH
    • 📖Asset classes
      • 🪙Cryptocurrencies
      • 💵Forex
      • 🛢️Commodities
    • 🎫Fees & Spread
    • 📰Pair List
    • 🧒How to use Practice Mode
    • ⚡One-Click Trading (1CT)
    • 🌌gTrade Solana
    • 📺Video tutorials
  • Loyalty Programs
    • Prime Trader
    • gTrade Credits
  • Community
    • gTrade Guardians
    • Governance forum
  • Reward Pools
    • 💚GNS Staking
    • 👛gToken Vaults
      • 👷Staker Functions
      • ❔Staker FAQ
      • ⏳Upgrades, updates, and timelocks
    • 🔼Active Pools & Incentives
  • Help
    • ❓FAQ
    • ⏳Chain congestion
  • Bridges
    • 🪐Arbitrum <-> Polygon Bridge
    • 🪐ERC20 Bridge (Polygon)
    • 🪐NFT Bridge (Polygon)
  • Developer
    • Integrators
      • Trading Contracts
      • Backend
      • Price Feed
      • Guides
        • v9 migration
        • Calculating borrowing fees
        • Calculating liquidation price
    • Technical Reference
      • Contracts
        • Changelogs
          • v9.2.1 Update
          • v9.1 Update
          • v9.1.1 Update
          • v9 Update
        • Core
          • Abstract
            • GNSAddressStore
            • GNSDiamondCut
            • GNSDiamondLoupe
            • GNSDiamondStorage
          • Facets
            • GNSBorrowingFees
            • GNSOtc
            • GNSPriceAggregator
            • GNSTradingInteractions
            • GNSTriggerRewards
            • GNSFeeTiers
            • GNSPairsStorage
            • GNSPriceImpact
            • GNSReferrals
            • GNSTradingCallbacks
            • GNSTradingStorage
          • GNSMultiCollatDiamond
          • GNSStaking
          • GToken
          • GTokenOpenPnlFeed
        • Interfaces
          • Libraries
            • IBorrowingFeesUtils
            • IOtcUtils
            • IPriceAggregatorUtils
            • ITriggerRewardsUtils
            • IFeeTiersUtils
            • IPairsStorageUtils
            • IPriceImpactUtils
            • IReferralsUtils
            • ITradingCallbacksUtils
            • ITradingCommonUtils
            • ITradingInteractionsUtils
            • ITradingStorageUtils
            • IUpdateLeverageUtils
            • IUpdatePositionSizeUtils
          • Types
            • IAddressStore
            • IBorrowingFees
            • IDiamondStorage
            • IOtc
            • IPriceAggregator
            • ITradingStorage
            • ITradingInteractions
            • ITriggerRewards
            • ITypes
            • IUpdateLeverage
            • IPairsStorage
            • IFeeTiers
            • IPriceImpact
            • IReferrals
            • ITradingCallbacks
            • IUpdatePositionSize
          • IChainlinkFeed
          • IArbSys
          • IChainlinkOracle
          • IERC20
          • IERC721
          • IERC721Design
          • IGeneralErrors
          • IGNSAddressStore
          • IGNSDiamond
          • IGNSDiamondCut
          • IGNSMultiCollatDiamond
          • IGNSDiamondLoupe
          • IGNSStaking
          • IGToken
          • IGTokenLockedDepositNft
          • IGTokenOpenPnlFeed
          • IGTokenLockedDepositNftDesign
          • ILiquidityPool
          • IRateProvider
          • IOwnable
        • Libraries
          • updateLeverage
            • UpdateLeverageLifecycles
          • updatePositionSize
            • IncreasePositionSizeUtils
            • DecreasePositionSizeUtils
            • UpdatePositionSizeLifecycles
          • AddressStoreUtils
          • ChainlinkClientUtils
          • ChainUtils
          • ConstantsUtils
          • CollateralUtils
          • DiamondUtils
          • LiquidityPoolUtils
          • OtcUtils
          • PackingUtils
          • StorageUtils
          • TriggerRewardsUtils
          • ArrayGetters
          • BorrowingFeesUtils
          • FeeTiersUtils
          • PriceAggregatorUtils
          • PriceImpactUtils
          • ReferralsUtils
          • TradingCallbacksUtils
          • PairsStorageUtils
          • TradingCommonUtils
          • TradingStorageUtils
          • TradingInteractionsUtils
        • Misc
          • EpochBasedTokenClaim
          • GNSCompensationHandler
          • GTokenRateProvider
          • GTokenLockedDepositNftDesign
          • ManagerTimelock
          • OwnerTimelock
          • VotingDelegator
        • Tokens
          • GainsNetworkToken
          • GTokenLockedDepositNft
      • Backend
        • Backend Types
      • SDK
        • Client Types
  • Archived
    • 🖼️gFARM2 NFTs
Powered by GitBook
On this page
  • getPnlPercent
  • Parameters
  • getPositionSizeCollateral
  • Parameters
  • getMarketExecutionPrice
  • Parameters
  • convertCollateralToUsd
  • Parameters
  • convertCollateralToGns
  • Parameters
  • getTradeValuePure
  • Parameters
  • getLiqPnlThresholdP
  • Parameters
  • getMinPositionSizeCollateral
  • Parameters
  • getPositionSizeCollateralBasis
  • Parameters
  • isWithinExposureLimits
  • Parameters
  • getTradeBorrowingFeeCollateral
  • Parameters
  • getTradeLiquidationPrice
  • Parameters
  • getTradeValueCollateral
  • Parameters
  • getTradeOpeningPriceImpact
  • Parameters
  • getTradeClosingPriceImpact
  • Parameters
  • getTradeLiqPnlThresholdP
  • Parameters
  • getTotalTradeFeesCollateral
  • Parameters
  • getTradeFeesCollateral
  • Parameters
  • getMinGovFeeCollateral
  • revertIfTradeHasPendingMarketOrder
  • Parameters
  • getGToken
  • Parameters
  • transferCollateralFrom
  • Parameters
  • transferCollateralTo
  • Parameters
  • transferGnsTo
  • Parameters
  • transferGnsFrom
  • Parameters
  • sendCollateralToVault
  • Parameters
  • handleTradePnl
  • Parameters
  • updateFeeTierPoints
  • Parameters
  • distributeVaultFeeCollateral
  • Parameters
  • distributeExactGovFeeCollateral
  • Parameters
  • distributeGnsOtcFeeCollateral
  • Parameters
  • distributeTriggerFeeGns
  • Parameters
  • processFees
  • Parameters
  • distributeReferralFeeCollateral
  • Parameters
  • updateOi
  • Parameters
  • updateOiTrade
  • Parameters
  • handleOiDelta
  • Parameters
  • _getMultiCollatDiamond

Was this helpful?

  1. Developer
  2. Technical Reference
  3. Contracts
  4. Libraries

TradingCommonUtils

External library for helper functions commonly used in many places

getPnlPercent

function getPnlPercent(uint64 _openPrice, uint64 _currentPrice, bool _long, uint24 _leverage) public pure returns (int256 p)

Returns the current percent profit of a trade (1e10 precision)

Parameters

Name
Type
Description

_openPrice

uint64

trade open price (1e10 precision)

_currentPrice

uint64

trade current price (1e10 precision)

_long

bool

true for long, false for short

_leverage

uint24

trade leverage (1e3 precision)

getPositionSizeCollateral

function getPositionSizeCollateral(uint120 _collateralAmount, uint24 _leverage) public pure returns (uint256)

Returns position size of trade in collateral tokens (avoids overflow from uint120 collateralAmount)

Parameters

Name
Type
Description

_collateralAmount

uint120

collateral of trade

_leverage

uint24

leverage of trade (1e3)

getMarketExecutionPrice

function getMarketExecutionPrice(uint256 _price, uint256 _spreadP, bool _long, bool _open, enum ITradingStorage.ContractsVersion _contractsVersion) public pure returns (uint256)

Calculates market execution price for a trade (1e10 precision)

Parameters

Name
Type
Description

_price

uint256

price of the asset (1e10)

_spreadP

uint256

spread percentage (1e10)

_long

bool

true if long, false if short

_open

bool

_contractsVersion

enum ITradingStorage.ContractsVersion

convertCollateralToUsd

function convertCollateralToUsd(uint256 _collateralAmount, uint128 _collateralPrecisionDelta, uint256 _collateralPriceUsd) public pure returns (uint256)

Converts collateral value to USD (1e18 precision)

Parameters

Name
Type
Description

_collateralAmount

uint256

amount of collateral (collateral precision)

_collateralPrecisionDelta

uint128

precision delta of collateral (10^18/10^decimals)

_collateralPriceUsd

uint256

price of collateral in USD (1e8)

convertCollateralToGns

function convertCollateralToGns(uint256 _collateralAmount, uint128 _collateralPrecisionDelta, uint256 _gnsPriceCollateral) internal pure returns (uint256)

Converts collateral value to GNS (1e18 precision)

Parameters

Name
Type
Description

_collateralAmount

uint256

amount of collateral (collateral precision)

_collateralPrecisionDelta

uint128

precision delta of collateral (10^18/10^decimals)

_gnsPriceCollateral

uint256

price of GNS in collateral (1e10)

getTradeValuePure

function getTradeValuePure(uint256 _collateral, int256 _percentProfit, uint256 _feesCollateral, uint128 _collateralPrecisionDelta) public pure returns (uint256)

Calculates trade value (useful when closing a trade) Important: does not calculate if trade can be liquidated or not, has to be done by calling function

Parameters

Name
Type
Description

_collateral

uint256

amount of collateral (collateral precision)

_percentProfit

int256

profit percentage (1e10)

_feesCollateral

uint256

borrowing fee + closing fee in collateral tokens (collateral precision)

_collateralPrecisionDelta

uint128

precision delta of collateral (10^18/10^decimals)

getLiqPnlThresholdP

function getLiqPnlThresholdP(struct IPairsStorage.GroupLiquidationParams _params, uint256 _leverage) public pure returns (uint256)

Pure function that returns the liquidation pnl % threshold for a trade (1e10)

Parameters

Name
Type
Description

_params

trade liquidation params

_leverage

uint256

trade leverage (1e3 precision)

getMinPositionSizeCollateral

function getMinPositionSizeCollateral(uint8 _collateralIndex, uint256 _pairIndex) public view returns (uint256)

Returns minimum position size in collateral tokens for a pair (collateral precision)

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_pairIndex

uint256

pair index

getPositionSizeCollateralBasis

function getPositionSizeCollateralBasis(uint8 _collateralIndex, uint256 _pairIndex, uint256 _positionSizeCollateral) public view returns (uint256)

Returns position size to use when charging fees

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_pairIndex

uint256

pair index

_positionSizeCollateral

uint256

trade position size in collateral tokens (collateral precision)

isWithinExposureLimits

function isWithinExposureLimits(uint8 _collateralIndex, uint16 _pairIndex, bool _long, uint256 _positionSizeCollateralDelta) external view returns (bool)

Checks if total position size is not higher than maximum allowed open interest for a pair

Parameters

Name
Type
Description

_collateralIndex

uint8

index of collateral

_pairIndex

uint16

index of pair

_long

bool

true if long, false if short

_positionSizeCollateralDelta

uint256

position size delta in collateral tokens (collateral precision)

getTradeBorrowingFeeCollateral

function getTradeBorrowingFeeCollateral(struct ITradingStorage.Trade _trade) public view returns (uint256)

Convenient wrapper to return trade borrowing fee in collateral tokens (collateral precision)

Parameters

Name
Type
Description

_trade

trade input

getTradeLiquidationPrice

function getTradeLiquidationPrice(struct ITradingStorage.Trade _trade, bool _useBorrowingFees) public view returns (uint256)

Convenient wrapper to return trade liquidation price (1e10)

Parameters

Name
Type
Description

_trade

trade input

_useBorrowingFees

bool

getTradeValueCollateral

function getTradeValueCollateral(struct ITradingStorage.Trade _trade, int256 _percentProfit, uint256 _closingFeesCollateral, uint128 _collateralPrecisionDelta) public view returns (uint256 valueCollateral, uint256 borrowingFeesCollateral)

Returns trade value and borrowing fee in collateral tokens

Parameters

Name
Type
Description

_trade

trade data

_percentProfit

int256

profit percentage (1e10)

_closingFeesCollateral

uint256

closing fees in collateral tokens (collateral precision)

_collateralPrecisionDelta

uint128

precision delta of collateral (10^18/10^decimals)

getTradeOpeningPriceImpact

function getTradeOpeningPriceImpact(struct ITradingCommonUtils.TradePriceImpactInput _input, enum ITradingStorage.ContractsVersion _contractsVersion) external view returns (uint256 priceImpactP, uint256 priceAfterImpact)

Returns price impact % (1e10), price after spread and impact (1e10)

Parameters

Name
Type
Description

_input

input data

_contractsVersion

enum ITradingStorage.ContractsVersion

contracts version

getTradeClosingPriceImpact

function getTradeClosingPriceImpact(struct ITradingCommonUtils.TradePriceImpactInput _input) external view returns (uint256 priceImpactP, uint256 priceAfterImpact, uint256 tradeValueCollateralNoFactor)

Returns price impact % (1e10), price after spread and impact (1e10), and trade value used to know if pnl is positive (collateral precision)

Parameters

Name
Type
Description

_input

input data

getTradeLiqPnlThresholdP

function getTradeLiqPnlThresholdP(struct ITradingStorage.Trade _trade) public view returns (uint256)

Returns a trade's liquidation threshold % (1e10)

Parameters

Name
Type
Description

_trade

trade struct

getTotalTradeFeesCollateral

function getTotalTradeFeesCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _positionSizeCollateral) public view returns (uint256)

Returns all fees for a trade in collateral tokens

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_trader

address

address of trader

_pairIndex

uint16

index of pair

_positionSizeCollateral

uint256

position size in collateral tokens (collateral precision)

getTradeFeesCollateral

function getTradeFeesCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex, uint256 _collateralAmount, uint256 _positionSizeCollateral, enum ITradingStorage.PendingOrderType _orderType) public view returns (struct IPairsStorage.TradeFees tradeFees)

Returns all fees for a trade in collateral tokens

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_trader

address

address of trader

_pairIndex

uint16

index of pair

_collateralAmount

uint256

trade collateral amount (collateral precision)

_positionSizeCollateral

uint256

trade position size in collateral tokens (collateral precision)

_orderType

enum ITradingStorage.PendingOrderType

corresponding order type

getMinGovFeeCollateral

function getMinGovFeeCollateral(uint8 _collateralIndex, address _trader, uint16 _pairIndex) public view returns (uint256)

revertIfTradeHasPendingMarketOrder

function revertIfTradeHasPendingMarketOrder(address _user, uint32 _index) public view

Reverts if user initiated any kind of pending market order on his trade

Parameters

Name
Type
Description

_user

address

trade user

_index

uint32

trade index

getGToken

function getGToken(uint8 _collateralIndex) public view returns (contract IGToken)

Returns gToken contract for a collateral index

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

transferCollateralFrom

function transferCollateralFrom(uint8 _collateralIndex, address _from, uint256 _amountCollateral) public

Transfers collateral from trader

Parameters

Name
Type
Description

_collateralIndex

uint8

index of the collateral

_from

address

sending address

_amountCollateral

uint256

amount of collateral to receive (collateral precision)

transferCollateralTo

function transferCollateralTo(uint8 _collateralIndex, address _to, uint256 _amountCollateral) internal

Transfers collateral to trader

Parameters

Name
Type
Description

_collateralIndex

uint8

index of the collateral

_to

address

receiving address

_amountCollateral

uint256

amount of collateral to transfer (collateral precision)

transferGnsTo

function transferGnsTo(address _to, uint256 _amountGns) internal

Transfers GNS to address

Parameters

Name
Type
Description

_to

address

receiving address

_amountGns

uint256

amount of GNS to transfer (1e18)

transferGnsFrom

function transferGnsFrom(address _from, uint256 _amountGns) internal

Transfers GNS from address

Parameters

Name
Type
Description

_from

address

sending address

_amountGns

uint256

amount of GNS to receive (1e18)

sendCollateralToVault

function sendCollateralToVault(uint8 _collateralIndex, uint256 _amountCollateral, address _trader) public

Sends collateral to gToken vault for negative pnl

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_amountCollateral

uint256

amount of collateral to send to vault (collateral precision)

_trader

address

trader address

handleTradePnl

function handleTradePnl(struct ITradingStorage.Trade _trade, int256 _collateralSentToTrader, int256 _availableCollateralInDiamond, uint256 _borrowingFeeCollateral) external returns (uint256 traderDebt)

Handles pnl transfers when (fully or partially) closing a trade

Parameters

Name
Type
Description

_trade

trade struct

_collateralSentToTrader

int256

total amount to send to trader (collateral precision)

_availableCollateralInDiamond

int256

part of _collateralSentToTrader available in diamond balance (collateral precision)

_borrowingFeeCollateral

uint256

updateFeeTierPoints

function updateFeeTierPoints(uint8 _collateralIndex, address _trader, uint256 _pairIndex, uint256 _positionSizeCollateral) public

Updates a trader's fee tiers points based on his trade size

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_trader

address

address of trader

_pairIndex

uint256

index of pair

_positionSizeCollateral

uint256

position size in collateral tokens (collateral precision)

distributeVaultFeeCollateral

function distributeVaultFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _valueCollateral) public

Distributes fee to gToken vault

Parameters

Name
Type
Description

_collateralIndex

uint8

index of collateral

_trader

address

address of trader

_valueCollateral

uint256

fee in collateral tokens (collateral precision)

distributeExactGovFeeCollateral

function distributeExactGovFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _govFeeCollateral) public

Distributes gov fees exact amount

Parameters

Name
Type
Description

_collateralIndex

uint8

index of collateral

_trader

address

address of trader

_govFeeCollateral

uint256

position size in collateral tokens (collateral precision)

distributeGnsOtcFeeCollateral

function distributeGnsOtcFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _amountCollateral) public

Increases OTC balance to be distributed once OTC is executed

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_trader

address

trader address

_amountCollateral

uint256

amount of collateral tokens to distribute (collateral precision)

distributeTriggerFeeGns

function distributeTriggerFeeGns(address _trader, uint8 _collateralIndex, uint256 _triggerFeeCollateral, uint256 _gnsPriceCollateral, uint128 _collateralPrecisionDelta) public

Distributes trigger fee in GNS tokens

Parameters

Name
Type
Description

_trader

address

address of trader

_collateralIndex

uint8

index of collateral

_triggerFeeCollateral

uint256

trigger fee in collateral tokens (collateral precision)

_gnsPriceCollateral

uint256

gns/collateral price (1e10 precision)

_collateralPrecisionDelta

uint128

collateral precision delta (10^18/10^decimals)

processFees

function processFees(struct ITradingStorage.Trade _trade, uint256 _positionSizeCollateral, enum ITradingStorage.PendingOrderType _orderType) external returns (uint256)

Distributes opening fees for trade and returns the trade fees charged in collateral tokens

Parameters

Name
Type
Description

_trade

trade struct

_positionSizeCollateral

uint256

position size in collateral tokens (collateral precision)

_orderType

enum ITradingStorage.PendingOrderType

trade order type

distributeReferralFeeCollateral

function distributeReferralFeeCollateral(uint8 _collateralIndex, address _trader, uint256 _positionSizeCollateral, uint256 _referralFeeCollateral, uint256 _gnsPriceCollateral) public

Distributes referral rewards and returns the amount charged in collateral tokens

Parameters

Name
Type
Description

_collateralIndex

uint8

collateral index

_trader

address

address of trader

_positionSizeCollateral

uint256

position size in collateral tokens (collateral precision)

_referralFeeCollateral

uint256

referral fee in collateral tokens (collateral precision)

_gnsPriceCollateral

uint256

gns/collateral price (1e10 precision)

updateOi

function updateOi(struct ITradingStorage.Trade _trade, uint256 _positionSizeCollateral, bool _open, bool _isPnlPositive) public

_Update protocol open interest (any amount) CAREFUL: this will reset the trade's borrowing fees to 0 when open = true

Parameters

Name
Type
Description

_trade

trade struct

_positionSizeCollateral

uint256

position size in collateral tokens (collateral precision)

_open

bool

whether it corresponds to a trade opening or closing

_isPnlPositive

bool

whether it corresponds to a positive pnl trade (only relevant when _open = false)

updateOiTrade

function updateOiTrade(struct ITradingStorage.Trade _trade, bool _open, bool _isPnlPositive) external

_Update protocol open interest (trade position size) CAREFUL: this will reset the trade's borrowing fees to 0 when open = true

Parameters

Name
Type
Description

_trade

trade struct

_open

bool

whether it corresponds to a trade opening or closing

_isPnlPositive

bool

whether it corresponds to a positive pnl trade (only relevant when _open = false)

handleOiDelta

function handleOiDelta(struct ITradingStorage.Trade _trade, uint256 _newPositionSizeCollateral, bool _isPnlPositive) external

Handles OI delta for an existing trade (for trade updates)

Parameters

Name
Type
Description

_trade

trade struct

_newPositionSizeCollateral

uint256

new position size in collateral tokens (collateral precision)

_isPnlPositive

bool

whether it corresponds to a positive pnl trade (only relevant when closing)

_getMultiCollatDiamond

function _getMultiCollatDiamond() internal view returns (contract IGNSMultiCollatDiamond)

Returns current address as multi-collateral diamond interface to call other facets functions.

PreviousPairsStorageUtilsNextTradingStorageUtils

Last updated 7 months ago

Was this helpful?

ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
ITradingStorage.Trade
IPairsStorage.GroupLiquidationParams
ITradingCommonUtils.TradePriceImpactInput
ITradingCommonUtils.TradePriceImpactInput