MCDEX
Search…
Collateral
This guide shows how to calculate position with giving collateral amount by using the queryTrade function.

Calculate position with giving collateral amount

Can reference Trade to know how to use queryTrade

Example

Get left bound and right bound of position with default leverage and collateral.
Can reference Get Perpetual Info to get perpetual object.
let markPrice = perpetual.markPrice
let collateral = new BigNumber(3500)
let leverage = new BigNumber(5)
let rPos: BigNumber = (collateral.div(markPrice)).times(leverage.plus(1)) // plus 1 to expand upper bound
let lPos: BigNumber = collateral.div(markPrice)
Using binary search for position.
async function searchPos(lPos: BigNumber, rPos: BigNumber, collateral: BigNumber, iteration: number): Promise<string> {
while (iteration > 0) {
// l + (r-l)/2 for preventing over flow, instead of (l+r)/2
let pos = lPos.plus(((rPos.minus(lPos)).div(2)))
console.log("rPos " + rPos)
console.log("lPos " + lPos)
console.log("pos " + pos)
// 1 leverage
let res = await liquidityPool.connect(signer).callStatic.queryTrade(0, signer.address, toWei(pos.toString()), NONE, 12800)
let costBigNumber = new BigNumber(fromWei(res.cost.toString()))
console.log("costBigNumber " + costBigNumber)
if (costBigNumber.eq(collateral)) {
return pos.toString()
} else if (costBigNumber.gt(collateral)) {
// means pos too much
rPos = pos
} else if (costBigNumber.lt(collateral)) {
// means pos too small
lPos = pos
}
iteration = iteration - 1
}
return lPos.plus(((rPos.minus(lPos)).div(2))).toString()
}

Sample Code

Copy link
On this page
Calculate position with giving collateral amount
Example
Sample Code