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.
1
let markPrice = perpetual.markPrice
2
let collateral = new BigNumber(3500)
3
let leverage = new BigNumber(5)
4
let rPos: BigNumber = (collateral.div(markPrice)).times(leverage.plus(1)) // plus 1 to expand upper bound
5
let lPos: BigNumber = collateral.div(markPrice)
Copied!
Using binary search for position.
1
async function searchPos(lPos: BigNumber, rPos: BigNumber, collateral: BigNumber, iteration: number): Promise<string> {
2
while (iteration > 0) {
3
// l + (r-l)/2 for preventing over flow, instead of (l+r)/2
4
let pos = lPos.plus(((rPos.minus(lPos)).div(2)))
5
console.log("rPos " + rPos)
6
console.log("lPos " + lPos)
7
console.log("pos " + pos)
8
// 1 leverage
9
let res = await liquidityPool.connect(signer).callStatic.queryTrade(0, signer.address, toWei(pos.toString()), NONE, 12800)
10
let costBigNumber = new BigNumber(fromWei(res.cost.toString()))
11
console.log("costBigNumber " + costBigNumber)
12
13
if (costBigNumber.eq(collateral)) {
14
return pos.toString()
15
} else if (costBigNumber.gt(collateral)) {
16
// means pos too much
17
rPos = pos
18
} else if (costBigNumber.lt(collateral)) {
19
// means pos too small
20
lPos = pos
21
}
22
iteration = iteration - 1
23
}
24
return lPos.plus(((rPos.minus(lPos)).div(2))).toString()
25
}
Copied!

Sample Code

Last modified 5d ago