MCDEX
Search…
Re-Margin
This guide shows how to re-margin with specific leverage (EX: 3). In order to set target leverage, calculate current leverage first, then execute deposit or withdraw function
Can reference Get Account to know how to get account object & Get Perpetual Info to know how to get perpetual object

Function

  1. 1.
    deposit: can reference Adding Margin to know more.
  2. 2.
    withdraw: can reference Removing Margin to know more.

Example

Calculate the current leverage first.
1
const markPrice = perpetual.markPrice
2
const keeperGasReward = perpetual.keeperGasReward
3
const position = fromWei(account.accountStorage.position)
4
const margin = fromWei(account.accountStorage.margin)
5
const oi = markPrice * Math.abs(Number(position))
6
const leverage = oi / (Number(margin) - keeperGasReward)
7
console.log("now leverage: " + leverage)
Copied!
In order to set leverage to 3, execute the difference amount, then calling deposit or withdraw.
1
const targetMargin = oi / 3 + keeperGasReward
2
console.log("targetMargin: " + targetMargin)
3
if (targetMargin > Number(margin)) {
4
const amount = targetMargin - Number(margin)
5
console.log("deposit amount: " + amount)
6
await liquidityPool.deposit(0, trader.address, toWei(amount.toString()))
7
} else if (targetMargin < Number(margin)) {
8
const amount = Number(margin) - targetMargin
9
console.log("withdraw amount: " + amount)
10
await liquidityPool.withdraw(0, trader.address, toWei(amount.toString()))
11
}
Copied!

Sample Code

ReMargin
Last modified 23d ago