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
  • TradeContainer
  • Fee
  • Context
  • Calculate liquidation price

Was this helpful?

  1. Developer
  2. Integrators
  3. Guides

Calculating liquidation price

Learn how to calculate any trade's liquidation price

PreviousCalculating borrowing feesNextTechnical Reference

Last updated 9 months ago

Was this helpful?

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 getLiquidationPrice() function.

getLiquidationPrice: (trade: , fee: , initialAccFees: , context: GetLiquidationPriceContext) => number;

TradeContainer

To calculate trade's liquidation price, we need to find a trade and its first. TradeContainer is unique object per single trade and is containing all its information.

By inspecting allTrades of backend's response, we're able to find all open trades & orders (each represented by single, unique object). Lets pick last market trade (trade.type = 0 ) at time of writing this guide, which is:

{
    "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"
    }
}
{
    "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

With pairs and trade's pairIndex we compute feeIndex:

pairs[trade.pairIndex].feeIndex

{
    "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.

type GetLiquidationPriceContext = {
    currentBlock: number;
    groups: BorrowingFeeGroup[];
    pairs: BorrowingFeePair[];
    liquidationParams: LiquidationParams | undefined;
    pairSpreadP: number | undefined;
    collateralPriceUsd: number | undefined;
    contractsVersion: ContractsVersion | undefined;
}

currentBlock

tradingVariables.currentBlock

groups and pairs

tradingVariables.collaterals[trade.collateralIndex - 1].borrowingFees

liquidationParams

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

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

tradeInfo.contractsVersion

At the end, the context passed to getLiquidationPrice() should look similar to this:

{
    "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:

This response is of type, therefore we need to properly convert it to type first (SDK uses ). Converted and normalised trade will look like this:

Lets focus on second getLiquidationPrice() argument now, which is .

To find proper object, we need to compute feeIndex for given trade first. By calling backend's we're getting pairs and fees arrays.

Remember that backend values should be normalised, see vs and vs

Now we are able to find our by simply accessing fees[feeIndex]. Resulting object should look similar to this:

There are few context parameters that we can pass here. All of them are coming from backend's endpoint or discussed above.

Its current block of underlying network. Use any valid block or backend's response:

To get groups and pairs we need to inspect collaterals backend response. It is an array of objects corresponding to each supported collateral. Use trade.collateralIndex to select proper collateral object, then access its borrowingFees:

Remember that backend values should be normalised, see vs

Available directly on

Should be normalised, see vs

Available on :

TradeContainer
TradeContainer
SDK's
client types
TradeContainer
TradingContainerBackend
TradeContainerBackend
PairBackend
FeeBackend
PairParamsBorrowingFeesBackend
PairBackend
TradeContainer
Fee
Pair
Fee
Fee
PairParamsBorrowingFees
Pair
Trade
Fee
InitialAccFees
TradeContainer
Fee
/trading-variables
/trading-variables
/trading-variables
/trading-variables
/trading-variables